当前位置:网站首页>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();
}
}
边栏推荐
- 施努卡:机器视觉定位技术 机器视觉定位原理
- 555电路详解
- leetcode-304:二维区域和检索 - 矩阵不可变
- Guid primary key
- Talking about the return format in the log, encapsulation format handling, exception handling
- How embedded engineers improve work efficiency
- A small problem of bit field and symbol expansion
- LLVM之父Chris Lattner:為什麼我們要重建AI基礎設施軟件
- 【作业】2022.7.6 写一个自己的cal函数
- Postman interface test VI
猜你喜欢
ArcGIS operation: converting DWG data to SHP data
基于HPC场景的集群任务调度系统LSF/SGE/Slurm/PBS
LLVM之父Chris Lattner:為什麼我們要重建AI基礎設施軟件
优雅的 Controller 层代码
JMeter loop controller and CSV data file settings are used together
Inno setup packaging and signing Guide
Fiddler break point
Some properties of leetcode139 Yang Hui triangle
Embedded background - chip
P2788 数学1(math1)- 加减算式
随机推荐
IO模型复习
Use of JSON extractor originals in JMeter
[detailed explanation of Huawei machine test] tall and short people queue up
Word自动生成目录的方法
XML configuration file parsing and modeling
电表远程抄表拉合闸操作命令指令
The Hal library is configured with a general timer Tim to trigger ADC sampling, and then DMA is moved to the memory space.
I'd rather say simple problems a hundred times than do complex problems once
Embedded background - chip
Talking about the return format in the log, encapsulation format handling, exception handling
IPv4套接字地址结构
Guid primary key
leetcode-560:和为 K 的子数组
leetcode-304:二维区域和检索 - 矩阵不可变
Weekly recommended short videos: what are the functions of L2 that we often use in daily life?
P1031 [NOIP2002 提高组] 均分纸牌
Appx代碼簽名指南
Leetcode exercise - 113 Path sum II
P1223 排队接水/1319:【例6.1】排队接水
STM32 ADC和DMA