Contents

实现List, RandomAccess, Cloneable, java.io.Serializable 接口

1
2
3
4
5
/** The lock protecting all mutators */
final transient ReentrantLock lock = new ReentrantLock();

/** The array, accessed only via getArray/setArray. */
private transient volatile Object[] array;

主要的成员变量有2个,一个ReentrantLock,一个是内部存值的数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}

Add方法,先是前后两个lock与unlock,保证安全性。
实现实际上是复制一个原来数组,将新值添加到新数组的最后一位,内部变量指向新的数组。

1
2
3
4
5
6
7
8
9
10
static final class COWIterator<E> implements ListIterator<E> {
/** Snapshot of the array */
private final Object[] snapshot;
/** Index of element to be returned by subsequent call to next. */
private int cursor;

private COWIterator(Object[] elements, int initialCursor) {
cursor = initialCursor;
snapshot = elements;
}

内部的遍历,其实是将原来数组进行一个快照,这样即使数组变化了,不影响快照的遍历。

CopyOnWriteArrayList 的添加元素很消耗资源,因为每次都要新建一个数组,然后复制所有数据,只适用于读远大于写的情况,如果写比较多,性能会很差。

Contents