標籤:os io java ar sp on c new ad
CopyOnWriteArrayList是jdk1.5並法包裡面用於處理高並發下,讀多寫少的情況下,降低鎖等待的集合類。下面對該類實現做一個簡要的分析
1,首先CopyOnWriteArrayList是實現了List介面,對=List介面的相關方法進行了實現。
2,下面的它的add方法,會首先加鎖,然後copy原List內部的數組,然後對新數組長度加1後釋放鎖。由於數組copy速度很快,切在讀多寫少的情況下鎖開銷比較少
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(); } }
2,它的迭代器COWIterator不是快速失敗的,下面是它的源碼
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++]; }
3,下面是它的remove方法,加鎖原理同add方法
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(); } }
jdk並發包 CopyOnWriteArrayList源碼分析