CopyOnWrite容器類
CopyOnWrite(COW)容器類適用于讀多寫少的場合,器如其名,多線程可以并發(fā)讀取(迭代讀取,不包括get()),但是寫入的時候是直接就重新復(fù)制一個新的數(shù)據(jù)結(jié)構(gòu)來替換容器里原來的那個數(shù)據(jù)結(jié)構(gòu)
比如CopyOnWriteArrayList,本身是通過數(shù)組來實現(xiàn)的,讀的時候是不加鎖的(迭代),和ArrayList沒什么區(qū)別,但是寫的時候是加鎖復(fù)制的,下面是add()的時候的代碼:
public void add(int index, E element) {
//獲取成員變量里的ReentratLock
final ReentrantLock lock = this.lock;
//加鎖
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
if (index > len || index < 0)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+len);
Object[] newElements;
//長度減去當前增加的元素的index
int numMoved = len - index;
if (numMoved == 0)
//如果等于0,說明數(shù)組長度不夠了,需要復(fù)制并且把數(shù)組長度增加1
newElements = Arrays.copyOf(elements, len + 1);
else {
//這里的情況就是在原來的數(shù)組中間插入一個元素..扎心了,分兩步復(fù)制,騰出index的位置給要傳入的元素
newElements = new Object[len + 1];
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index, newElements, index + 1,
numMoved);
//在ArrayList的實現(xiàn)是
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
//因為ArrayList在數(shù)組長度充足的情況下是在組內(nèi)從index的位置向后復(fù)制,騰出位置給index上要插入的元素
//以上是ArrayList的實現(xiàn)
}
//將index元素的位置插入進去
newElements[index] = element;
//更新新的數(shù)組
setArray(newElements);
} finally {
//釋放鎖
lock.unlock();
}
}
加鎖的意義是在任意一個時刻,都只有一個線程可以去修改(包括add,remove)容器,一旦去修改容器,會重新復(fù)制一個底層儲存數(shù)據(jù)的結(jié)構(gòu)(這里就是復(fù)制數(shù)組),然后把這個復(fù)制的數(shù)組的引用傳遞給容器的成員變量(volatile修飾,可以保證內(nèi)存可見性).
再來看看迭代的時候是如何操作的,COWAL里的迭代器叫COWIterator
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;
//直接把容器里儲存數(shù)據(jù)的數(shù)組引用給Iterator里的成員變量
private COWIterator(Object[] elements, int initialCursor) {
cursor = initialCursor;
snapshot = elements;
}
public boolean hasNext() {
return cursor < snapshot.length;
}
public boolean hasPrevious() {
return cursor > 0;
}
//和ArrayList最大的區(qū)別是沒有mod的檢查
@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;
}
/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; {@code remove}
* is not supported by this iterator.
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; {@code set}
* is not supported by this iterator.
*set和add還有remove方法都是不支持的
*/
public void set(E e) {
throw new UnsupportedOperationException();
}
/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; {@code add}
* is not supported by this iterator.
*/
public void add(E e) {
throw new UnsupportedOperationException();
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
Object[] elements = snapshot;
final int size = elements.length;
for (int i = cursor; i < size; i++) {
@SuppressWarnings("unchecked") E e = (E) elements[i];
action.accept(e);
}
cursor = size;
}
}
從上面迭代的代碼可以看出來,CopyOnWriteArrayList的迭代器是不支持對數(shù)組進行修改的.修改只能通過容器本身去修改.
設(shè)想,如果a,b,c線程同時在迭代,并且d線程在修改容器,a,b,c線程迭代的時候讀取的是舊的數(shù)組對象,所以是不會像arrayList那樣拋出ConcurrentModificationException異常的,就是沒有了fail-fast機制,因為cow容器的思想就是通過延遲更新的,類似快照的思想來處理這種讀多改少的場合的.
此外,CopyOnWriteArrayList還有一個不同于ArrayList的方法
/**
*有點類似set方法的contains()方法,其實想想就明白,如果重復(fù)添加相同的元素
*,會觸發(fā)復(fù)制數(shù)組,如果不重復(fù)添加數(shù)組里已經(jīng)有的方法的話,就使用這個方法
**/
public boolean addIfAbsent(E e) {
Object[] snapshot = getArray();
//先通過indexOf方法判斷是否包含,如果不包含,進入addIfAbsent()嘗試添加
return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
addIfAbsent(e, snapshot);
}
/**addIfAbsent(e,sanpshot)方法
*
**/
private boolean addIfAbsent(E e, Object[] snapshot) {
final ReentrantLock lock = this.lock;
//鎖定
lock.lock();
try {
Object[] current = getArray();
int len = current.length;
//判斷在鎖定前是否被更改過,如果快照和當前不同,說明被改變了
if (snapshot != current) {
// Optimize for lost race to another addXXX operation
int common = Math.min(snapshot.length, len);
for (int i = 0; i < common; i++)
//先判斷當前與快照里的是否相同
//因為在進入這個方法前已經(jīng)判斷了不包含待插入元素
//只有快照里的元素和當前不同才說明被改變了,才有繼續(xù)比較下一步的意義
if (current[i] != snapshot[i] && eq(e, current[i]))
return false;
//再次從common位置開始判斷是否包含待添加的元素
if (indexOf(e, current, common, len) >= 0)
return false;
//其實上面兩次比較方法完全可以壓縮成第二個方法去比較的,可能是第一種不用頻繁調(diào)用equals方法,提高性能吧
}
//如果快照和當前相同,直接復(fù)制,在最后添加元素,完事
Object[] newElements = Arrays.copyOf(current, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
上述方法直接引出了另外一個COW類型的類,他就是CopyOnWriteSet
這貨說是Set,其實是聚合了一個CopyOnWriteArrayList成員變量來實現(xiàn)保存元素的
它的和Set接口有關(guān)的方法全部是調(diào)用CopyOnWriteArrayList的方法來實現(xiàn)的
所以他就是個套著Set馬甲的CopyOnWriteArrayList,這個應(yīng)該叫適配器模式嗎???
總而言之,COW類就是用在讀多寫少的場合,不保證數(shù)據(jù)的實時一致性,只保證數(shù)據(jù)在最終一致性(指系統(tǒng)長時間沒進行修改時的一致性)