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();
}
}
``
网友评论