CopyOnWriteArrayList是java.util.concurrent併發包下的集合類,與集合功能與ArrayList相似,主要區別爲這是線程安全類
如類名一樣,在對底層數組寫(修改)時,會複製一份數組進行實際操作,操作完成後修改引用爲新數組;而在讀的時候是直接讀取數組
接下來我們來看具體的源碼:
/** The lock protecting all mutators */
transient final ReentrantLock lock = new ReentrantLock();
/** The array, accessed only via getArray/setArray. */
private volatile transient Object[] array;
lock 所有的讀操作,都會使用這個可重入鎖保證線程安全,
array 就是實例當前的底層數組,保存着list的數據
transient是Java語言的關鍵字,用來表示一個域不是該對象串行化的一部分。當一個對象被串行化的時候,transient型變量的值不包括在串行化的表示中
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();
}
}
public E remove(int index) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
E oldValue = get(elements, index);
int numMoved = len - index - 1;
if (numMoved == 0)
setArray(Arrays.copyOf(elements, len - 1));
else {
Object[] newElements = new Object[len - 1];
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index + 1, newElements, index,
numMoved);
setArray(newElements);
}
return oldValue;
} finally {
lock.unlock();
}
}
基本每個寫操作都類似add方法這樣:先獲取鎖,然後複製數組,操作完成後,修改數組引用
讀操作方法基本都基本與ArrayList相似,直接讀取:
@SuppressWarnings("unchecked")
private E get(Object[] a, int index) {
return (E) a[index];
}
/**
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
return get(getArray(), index);
}
CopyOnWriteArrayList 讀操作很快,不用獲取鎖,但是可能獲取到的數據可能就是舊的(過期的),即存在延遲,特別是使用迭代器訪問
每次獲取迭代器時,迭代器實例得到一份當前的複製數組,後續實際數據改變了,已經獲取的迭代器不會感知
iterator 與 listIterator 都是返回一個COWIterator實例:
public Iterator<E> iterator() {
return new COWIterator<E>(getArray(), 0);
}
public ListIterator<E> listIterator() {
return new COWIterator<E>(getArray(), 0);
}
private static 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; //創建迭代器實例後,底層數組的修改不會感知
}
public boolean hasNext() {
return cursor < snapshot.length;
}
public boolean hasPrevious() {
return cursor > 0;
}
@SuppressWarnings("unchecked")
public E next() {
if (! hasNext())
throw new NoSuchElementException();
return (E) snapshot[cursor++];
}
@SuppressWarnings("unchecked")
public E previous() {
if (! hasPrevious())
throw new NoSuchElementException();
return (E) snapshot[--cursor];
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor-1;
}
public void remove() {
throw new UnsupportedOperationException();
}
public void set(E e) {
throw new UnsupportedOperationException();
}
public void add(E e) {
throw new UnsupportedOperationException();
}
}
從CopyOnWriteArrayList 的設計來看,這個線程安全集合類通過在寫時複製操作,達到了讀和寫的分離,
由於每次寫都需要複製一份,內存使用也多,複製也會耗時;
所以CopyOnWriteArrayList適合在讀操作較多的併發場景下使用,
在常用的add方法,提供了批量的addAll方法,使用批量的方法可以減少每次添加的複製;