当前位置:网站首页>ArrayList线程不安全和解决方案
ArrayList线程不安全和解决方案
2022-07-07 08:23:00 【HGW689】
我们通常说的Java中的fail-fast机制(快速失败机制),默认指的是Java集合中的一种错误检测机制,当多个线程对集合进行结构性的改变时,有可能会出发fail-fast机制,这个时候会抛出ConcurrentModificationException异常。
为什么ArrayList线程不安全?Vector却线程安全呢?让我们来一探究竟!
ArrayList:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
//ensureCapacityInternal()就是判断如果将当前的新元素加到列表后面,列表的elementData数组的大小是否满足,如果size + 1的这个需求长度大于了elementData这个数组的长度,那么就要对这个数组进行扩容
elementData[size++] = e;
return true;
}
Vector:
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
显而易见:在ArrayList中,elementData与size都是全局变量,但没有进行sychronization同步处理,elementData是共享的线程不安全的mutable可变数据。
那么如何解决LIst线程安全问题呢?
- Vector:Vector list = new Vector<>();
- Collections:List list = Collections.synchronizedList(new ArrayList());
- CopyOnWriteArrayList:List list = new CopyOnWriteArrayList<>();
我们来看看 CopyOnWriteArrayList 中的add()方法,原理是使用了 写时复制技术:
public boolean add(E e) {
final ReentrantLock lock = this.lock;
// 首先:加锁!
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
// 1、将内容复制了一份
Object[] newElements = Arrays.copyOf(elements, len + 1);
// 2、写入新的内容
newElements[len] = e;
// 3、合并
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
边栏推荐
猜你喜欢
[second on] [jeecgboot] modify paging parameters
Use the fetch statement to obtain the repetition of the last row of cursor data
OpenGL glLightfv 函数的应用以及光源的相关知识
Methods of adding centerlines and centerlines in SolidWorks drawings
Prototype object in ES6
Leetcode-304: two dimensional area and retrieval - matrix immutable
Review of the losers in the postgraduate entrance examination
使用U2-Net深层网络实现——证件照生成程序
STM32 ADC和DMA
Talking about the return format in the log, encapsulation format handling, exception handling
随机推荐
移动端通过设置rem使页面内容及字体大小自动调整
The method of word automatically generating directory
P1223 排队接水/1319:【例6.1】排队接水
对存储过程进行加密和解密(SQL 2008/SQL 2012)
1324:【例6.6】整数区间
使用U2-Net深层网络实现——证件照生成程序
2022.7.4DAY596
对word2vec的一些浅层理解
LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
【二开】【JeecgBoot】修改分页参数
学习记录——高精度加法和乘法
[sword finger offer] 42 Stack push in and pop-up sequence
Differences between MCU and MPU
The story of Plato and his three disciples: how to find happiness? How to find the ideal partner?
STM32 ADC和DMA
table宽度比tbody宽度大4px
555电路详解
A small problem of bit field and symbol expansion
Sword finger offer 38 Arrangement of strings [no description written]
Using U2 net deep network to realize -- certificate photo generation program