Java深入學習31:ArrayList並發異常以及解決方案
先看一個ArrayList多線程的下的案例。
該案例會出現一些異常的情況,,期中有兩個異常需要留意
public class ArrayListConcurrentTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { new Thread(()->{ list.add(UUID.randomUUID().toString().substring(0,8)); System.out.println(Thread.currentThread().getName() + "\t" +list); }).start(); } } } ----------------------------------------日志1---------------------------------------------
Thread-2 [null, 6237f3be]
Thread-0 [null, 6237f3be]
Thread-1 [null, 6237f3be]
main [null, 6237f3be]
----------------------------------------日志2---------------------------------------------
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at java.util.AbstractCollection.toString(AbstractCollection.java:461)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at colleaction.ArrayListConcurrentTest.lambda$main$0(ArrayListConcurrentTest.java:22)
at java.lang.Thread.run(Thread.java:748)
1- 出現了list元素為null和元素"丟失"的情況,這個不是我們期望的。
原因:首先 ArrayList 的 add 方法不是線程安全的。對於其中的 elementData[size++] = e操作,分為size++和數組賦值兩步操作,假設線程1執行了size++后(此時size=1,index=0),CPU時間片掛起;線程2進來執行size++和數組賦值(此時size=2,index=1);線程1獲取到CPU時間片,執行數組賦值(此時size=2,index=1);那么久出現了線程1和線程2同時對index=1進行了賦值,並導致index=0沒有被賦值的情況
##ArrayList類 public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }
2- 出現ConcurrentModificationExceptionThread異常
原因:我們在執行日志輸出 System.out.println(Thread.currentThread().getName() + "\t" +list) 時;使用的ArratLIst的Iterator的迭代器獲取list的每個元素;每迭代會實例化一個Iterator對象,其中有個變量預期修改次數 expectedModCount 默認等於list的修改次數 modCount;每次使用Iterator.next()迭代遍歷list時,都需要進行checkForComodification判斷(判斷modCount != expectedModCount);多線程下,會出現一種情況,線程1在遍歷list;與此同時,線程2在修改list(導致modCount++);那么線程1在便利獲取元素時會出現checkForComodification失敗的情況,此時拋出ConcurrentModificationException異常。
##ArrayList類 public Iterator<E> iterator() { return new Itr(); } ##ArrayList類的內部類Itr private class Itr implements Iterator<E> { int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); ...... } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
如何處理ArrayList異常
1- 使用Vector;
Vector類整體來說是線程安全;因為Vector對add以及內部的Iterator.next方法都加了 synchronized 關鍵字;其中add方法鎖的是Vector示例對象,內部類Iterator.next()中鎖的是Vector.this(其實就是Vector類當前的實例);所以這里add()方法和Iterator.next()方法互斥,不會出現ConcurrentModificationException異常。
##Vector類 public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; } ##Vector類中的內部類Itr 類 private class Itr implements Iterator<E> { int expectedModCount = modCount; public E next() { synchronized (Vector.this) { checkForComodification(); int i = cursor; if (i >= elementCount) throw new NoSuchElementException(); cursor = i + 1; return elementData(lastRet = i); } } }
2- 使用Collections.synchronizedList(new ArrayList<>())
3- 使用 CopyOnWriteArrayList
END