CopyOnWriteArrayList
2020-06-29 本文已影响0人
晨曦_lcq
ArrayList VS Vector VS CopyOnWriteArrayList
- ArrayList 线程不安全
- Vector 线程安全,但是用synchronized修饰的方法,性能不行
- CopyOnWriteArrayList 兼顾了线程安全和性能
继承关系
CopyOnWriteArrayList.png解析:
- 属性
final transient ReentrantLock lock = new ReentrantLock();
// 元素
private transient volatile Object[] array;
- 线程安全,操作元素都加了锁
public E set(int index, E element) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
E oldValue = get(elements, index);
if (oldValue != element) {
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len);
newElements[index] = element;
setArray(newElements);
} else {
// Not quite a no-op; ensures volatile write semantics
setArray(elements);
}
return oldValue;
} finally {
lock.unlock();
}
}
``