列表容器常見的有
ArrayList
和LinkedList
,然而二者都是非線程安全的,若應用場景對線程安全有需求,則可使用CopyOnWriteArrayList
來代替傳統的Vector
java
先看下類中定義的成員變量, 一個數組和一個鎖數組
/** The lock protecting all mutators */ final transient ReentrantLock lock = new ReentrantLock(); /** The array, accessed only via getArray/setArray. */ private transient volatile Object[] array;
array: 保存了列表中的數據安全
lock: 修改時加鎖,用於保證線程安全數據結構
底層數據結構依然是數組,相交於ArrayList
而言,少了一個表示數組長度的size
變量,獲取列表長度是經過下面的方法多線程
public int size() { return getArray().length; } final Object[] getArray() { return array; }
留一個問題:併發
爲何獲取鏈表的長度個ArrayList的使用姿式不一樣,這樣作有什麼好處源碼分析
讀數據,帶兩個疑問進行看源碼性能
先看實現源碼學習
private E get(Object[] a, int index) { return (E) a[index]; } /** * {@inheritDoc} * * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { return get(getArray(), index); }
結果比較清晰測試
private transient volatile Object[] array;
直接在源碼中加上一些註釋
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) { // 刪除最後一個元素時 //直接進行數組拷貝,而後將tables數組引用指向拷貝後的數組 setArray(Arrays.copyOf(elements, len - 1)); } else { // 建立一個新的數組,將舊數組內容拷貝到新數組中 // 而後將tables數組引用指向新的數組 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(); } }
從刪除的實現,可肯定如下幾點:
ArrayList
新增元素時,可能致使數組擴容;CopyOnWriteArrayList
在列表的修改時,採用數組拷貝,在新的數組上進行操做,從這點出發,應該不存在擴容的問題,由於每次修改都會致使數組的從新拷貝
從代碼出發,驗證上面的觀點
public void add(int index, E element) { 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; int numMoved = len - index; // 將原數組拷貝到新的數組中 if (numMoved == 0) { // 添加在最後一個 newElements = Arrays.copyOf(elements, len + 1); } else { // 添加到中間,須要兩次拷貝 newElements = new Object[len + 1]; System.arraycopy(elements, 0, newElements, 0, index); System.arraycopy(elements, index, newElements, index + 1, numMoved); } // 直接將數據添加到新的數組 newElements[index] = element; // 將tables引用指向新的數組 setArray(newElements); } finally { lock.unlock(); } }
從實現得出如下幾個結論
CopyOnWriteArrayList
沒有數組擴容一說,由於每次修改都會建立一個新的數組新增元素示意圖
在List的遍歷過程當中,新增,刪除or修改其中元素值時,會出現什麼問題?
先寫個測試demo
public class CopyOnWriteTest { List<String> list = new CopyOnWriteArrayList<>( new String[]{ "1", "2", "3", "4", "5", "6", "7", "8", "9" } ); private void modify() { new Thread(() -> { list.add(8, "a8"); list.remove(9); list.set(6, "6666"); System.out.println("----修改完成----"); }).start(); } @Test public void testModify() throws InterruptedException { Iterator<String> iterable = list.iterator(); int i = 0; while (iterable.hasNext()) { if (i++ == 1) { modify(); } else if (i == 4) { Thread.sleep(1000); } System.out.println("index: " + i + " value: " + iterable.next()); } Thread.sleep(1000); System.out.println(list); } }
輸出結果
index: 1 value: 1 index: 2 value: 2 index: 3 value: 3 ----修改完成---- index: 4 value: 4 index: 5 value: 5 index: 6 value: 6 index: 7 value: 7 index: 8 value: 8 index: 9 value: 9 [1, 2, 3, 4, 5, 6, 6666, 8, a8]
發如今迭代的過程當中,對列表進行修改,是不會影響迭代過程的,遍歷的依然是原來的數組;(順帶說一句,若是換成ArrayList會拋併發修改的異常)
探究下原理,主要是由於 CopyOnWriteArrayList
的迭代器的實現方式
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; } 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; } /** * 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. */ 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(); } }
從源碼分析可得知
List容器中,
Vector
和CopyOnWriteArrayList
都是線程安全的,下面則主要對比下二者的實現邏輯
Vector
CopyOnWriteArrayList
array
)ArrayList
低;讀取無鎖,因此讀的性能比Vector
高(沒有競爭)