当前位置:网站首页>ArrayList capacity expansion mechanism and thread safety
ArrayList capacity expansion mechanism and thread safety
2022-07-01 13:33:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
List Implementation steps of capacity expansion
Generally speaking, there are two steps :
1、 Capacity expansion
Copy the original array to another array with larger memory space
2、 Additive elements
Add new elements to the expanded array
Performance analysis
ArrayList As a dynamic array , Its internal elements are stored sequentially in the form of an array , So it is very suitable for random access . In addition to the tail, insert and delete elements , Performance tends to be relatively poor , For example, we insert an element in the middle , All subsequent elements need to be moved .
Source code analysis
The first ArrayList Some attributes defined in are posted for the following source code analysis
ArrayList Two construction methods of
1.ArrayList() 2.ArrayList(int initialCapacity)
No arguments structure :
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
Belt structure :
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
In nonparametric construction , Created an empty array , The length is 0
In parametric construction , If the passed in parameter is a positive integer, the size of the created array will be determined according to the passed in parameter , Otherwise abnormal
The way to expand capacity
Insert element function (boolean add(E e))
ArrayList When the insert element exceeds the predefined maximum value of the current array , The array needs to be expanded , The expansion process needs to call the underlying layer System.arraycopy() Method to perform a large number of array copy operations .
Paste the source code
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
see , Actually add The method is two steps ,
First step : Increase length
The second step : Add elements to the array
ensureCapacityInternal(int minCapacity) This method of increasing length
We saw this place , If the far array is empty when adding , Just give one 10 The length of , Otherwise, add one
ensureExplicitCapacity(int minCapacity)
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
Passing through this place is really increasing the length , When the required length is greater than the original array length, it needs to be expanded , On the contrary, there is no need to expand
This is where the attention is
int newCapacity = oldCapacity + (oldCapacity >> 1);
oldCapacity >> 1 Shift right operator Half the original length Plus the original length, that is, each expansion is the original 1.5 times
All the previous work is to determine the length of the new array , After confirmation, the old array copy Go to the new array , In this way, the expansion of the array is over
Everything above is ArrayList The first step of capacity expansion , There is nothing to say in the second step , Is to add the element to be added to the last bit of the array
ArrayList Security
Non-thread safety
1. stay add There will be thread safety problems during the capacity expansion of , ensureCapacityInternal(int minCapacity) There is a thread safety problem in this step
2. stay add Of elementData[size++] = e This code will also have thread safety problems when multithreading ,
There are two steps here :
elementData[size] = e;
size = size + 1;
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/131442.html Link to the original text :https://javaforall.cn
边栏推荐
- In the next stage of digital transformation, digital twin manufacturer Youyi technology announced that it had completed a financing of more than 300 million yuan
- Chen Yu (Aqua) - Safety - & gt; Cloud Security - & gt; Multicloud security
- 陈宇(Aqua)-安全->云安全->多云安全
- Shangtang technology crash: a script written at the time of IPO
- How much money do novices prepare to play futures? Is agricultural products OK?
- Anti fraud, refusing to gamble, safe payment | there are many online investment scams, so it's impossible to make money like this
- Social distance (cow infection)
- 受益互联网出海 汇量科技业绩重回高增长
- PG basics -- Logical Structure Management (trigger)
- Spark source code (V) how does dagscheduler taskscheduler cooperate with submitting tasks, and what is the corresponding relationship between application, job, stage, taskset, and task?
猜你喜欢
Colorful five pointed star SVG dynamic web page background JS special effect
[machine learning] VAE variational self encoder learning notes
What is the future development direction of people with ordinary education, appearance and family background? The career planning after 00 has been made clear
当你真的学会DataBinding后,你会发现“这玩意真香”!
终端识别技术和管理技术
龙蜥社区开源 coolbpf,BPF 程序开发效率提升百倍
洞态在某互联⽹⾦融科技企业的最佳落地实践
进入前六!博云在中国云管理软件市场销量排行持续上升
刘对(火线安全)-多云环境的风险发现
Introduction to reverse debugging PE structure input table output table 05/07
随机推荐
How much money do novices prepare to play futures? Is agricultural products OK?
JS discolored Lego building blocks
The stack size specified is too small, specify at least 328k
During Oracle CDC data transmission, the CLOB type field will lose its value during update. There is a value before update, but
香港科技大学李泽湘教授:我错了,为什么工程意识比上最好的大学都重要?
China NdYAG crystal market research conclusion and development strategy proposal report Ⓥ 2022 ~ 2028
SAP 智能机器人流程自动化(iRPA)解决方案分享
minimum spanning tree
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
1. Sum of two numbers: given an integer array num and an integer target value, please find the two integers whose sum is the target value target in the array and return their array subscripts
流量管理技术
焱融看 | 混合云时代下,如何制定多云策略
3.4 《数据库系统概论》之数据查询—SELECT(单表查询、连接查询、嵌套查询、集合查询、多表查询)
The 14th five year plan of China's environmental protection industry and the report on the long-term goals for 2035 Ⓖ 2022 ~ 2028
Feign & Eureka & zuul & hystrix process
Reasons for MySQL reporting 1040too many connections and Solutions
Investment analysis and prospect prediction report of global and Chinese p-nitrotoluene industry Ⓙ 2022 ~ 2027
Report on the "14th five year plan" and scale prospect prediction of China's laser processing equipment manufacturing industry Ⓢ 2022 ~ 2028
Introduction to reverse debugging PE structure input table output table 05/07
学历、长相、家境普通的人,未来的发展方向是什么?00后的职业规划都已经整得明明白白......