当前位置:网站首页>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();
}
}
边栏推荐
- Serial communication relay Modbus communication host computer debugging software tool project development case
- [second on] [jeecgboot] modify paging parameters
- 施努卡:机器视觉定位技术 机器视觉定位原理
- HDU-2196 树形DP学习笔记
- Leetcode exercise - 113 Path sum II
- 2022.7.6DAY598
- The method of word automatically generating directory
- JMeter loop controller and CSV data file settings are used together
- 原型与原型链
- Prototype and prototype chain
猜你喜欢
AHB bus in stm32_ Apb2 bus_ Apb1 bus what are these
[second on] [jeecgboot] modify paging parameters
openinstall与虎扑达成合作,挖掘体育文化产业数据价值
LLVM之父Chris Lattner:為什麼我們要重建AI基礎設施軟件
The method of word automatically generating directory
P1031 [NOIP2002 提高组] 均分纸牌
优雅的 Controller 层代码
Some properties of leetcode139 Yang Hui triangle
JMeter loop controller and CSV data file settings are used together
Using U2 net deep network to realize -- certificate photo generation program
随机推荐
Talking about the return format in the log, encapsulation format handling, exception handling
When there are pointer variable members in the custom type, the return value and parameters of the assignment operator overload must be reference types
Common shortcut keys in IDA
Review of the losers in the postgraduate entrance examination
Several schemes of building hardware communication technology of Internet of things
Encrypt and decrypt stored procedures (SQL 2008/sql 2012)
C logging method
MCU is the most popular science (ten thousand words summary, worth collecting)
JMeter installation
About hzero resource error (groovy.lang.missingpropertyexception: no such property: weight for class)
[STM32] solution to the problem that SWD cannot recognize devices after STM32 burning program
OpenGL glLightfv 函数的应用以及光源的相关知识
Five simple and practical daily development functions of chrome are explained in detail. Unlock quickly to improve your efficiency!
Hdu-2196 tree DP learning notes
Adb 实用命令(网络包、日志、调优相关)
Vs code specifies the extension installation location
Kotlin realizes wechat interface switching (fragment exercise)
Differences between MCU and MPU
【acwing】786. 第k个数
PDF文档签名指南