当前位置:网站首页>ArrayList thread insecurity and Solutions
ArrayList thread insecurity and Solutions
2022-07-07 10:30:00 【HGW689】
What we usually say Java Medium fail-fast Mechanism ( Fast failure mechanism ), Default means Java An error detection mechanism in a collection , When multiple threads make structural changes to the collection , It's possible to start fail-fast Mechanism , This time it will throw ConcurrentModificationException abnormal .
Why? ArrayList Thread unsafe ?Vector But thread safety ? Let's explore how !
ArrayList:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
//ensureCapacityInternal() Is to judge if the current new element is added to the list , List elementData Whether the size of the array meets , If size + 1 The length of this requirement is greater than elementData The length of this array , Then we need to expand the capacity of this array
elementData[size++] = e;
return true;
}
Vector:
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
Obvious : stay ArrayList in ,elementData And size It's all global variables , But it didn't happen sychronization Synchronous processing ,elementData Shared threads are unsafe mutable Variable data .
So how to solve LIst What about thread safety ?
- Vector:Vector list = new Vector<>();
- Collections:List list = Collections.synchronizedList(new ArrayList());
- CopyOnWriteArrayList:List list = new CopyOnWriteArrayList<>();
Let's see CopyOnWriteArrayList Medium add() Method , The principle is to use Copy on write technology :
public boolean add(E e) {
final ReentrantLock lock = this.lock;
// First : Lock !
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
// 1、 Copy the content
Object[] newElements = Arrays.copyOf(elements, len + 1);
// 2、 Write new content
newElements[len] = e;
// 3、 Merge
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
边栏推荐
猜你喜欢
随机推荐
Hdu-2196 tree DP learning notes
STM32 ADC和DMA
Sword finger offer 38 Arrangement of strings [no description written]
2022.7.3DAY595
1323:【例6.5】活动选择
The variables or functions declared in the header file cannot be recognized after importing other people's projects and adding the header file
JMeter about setting thread group and time
.NET配置系统
Socket通信原理和实践
leetcode-560:和为 K 的子数组
搭建物联网硬件通信技术几种方案
@Configuration, use, principle and precautions of transmission:
leetcode-304:二维区域和检索 - 矩阵不可变
5个chrome简单实用的日常开发功能详解,赶快解锁让你提升更多效率!
JS实现链式调用
When there are pointer variable members in the custom type, the return value and parameters of the assignment operator overload must be reference types
[higherhrnet] higherhrnet detailed heat map regression code of higherhrnet
Easyexcel read write simple to use
[dai6] mirror image of JZ27 binary tree
leetcode-303:区域和检索 - 数组不可变








