在前面一篇文章中提到,對Vector、ArrayList在迭代的時候若是同時對其進行修改就會拋出java.util.ConcurrentModificationException異常。下面咱們就來討論如下這個異常出現的緣由以及解決辦法。html
如下是本文目錄大綱:java
一.ConcurrentModificationException異常出現的緣由安全
二.在單線程環境下的解決辦法多線程
三.在多線程環境下的解決方法併發
轉載原文連接:http://www.cnblogs.com/dolphin0520/p/3933551.htmlthis
先看下面這段代碼:spa
1 public class Test { 2 public static void main(String[] args) { 3 ArrayList<Integer> list = new ArrayList<Integer>(); 4 list.add(2); 5 Iterator<Integer> iterator = list.iterator(); 6 while(iterator.hasNext()){ 7 Integer integer = iterator.next(); 8 if(integer==2) 9 list.remove(integer); 10 } 11 } 12 }
運行結果:.net
從異常信息能夠發現,異常出如今checkForComodification()方法中。線程
咱們不忙看checkForComodification()方法的具體實現,咱們先根據程序的代碼一步一步看ArrayList源碼的實現:code
首先看ArrayList的iterator()方法的具體實現,查看源碼發如今ArrayList的源碼中並無iterator()這個方法,那麼很顯然這個方法應該是其父類或者實現的接口中的方法,咱們在其父類AbstractList中找到了iterator()方法的具體實現,下面是其實現代碼:
public Iterator<E> iterator() { return new Itr(); }
從這段代碼能夠看出返回的是一個指向Itr類型對象的引用,咱們接着看Itr的具體實現,在AbstractList類中找到了Itr類的具體實現,它是AbstractList的一個成員內部類,下面這段代碼是Itr類的全部實現:
1 private class Itr implements Iterator<E> { 2 int cursor = 0; 3 int lastRet = -1; 4 int expectedModCount = modCount; 5 public boolean hasNext() { 6 return cursor != size(); 7 } 8 public E next() { 9 checkForComodification(); 10 try { 11 E next = get(cursor); 12 lastRet = cursor++; 13 return next; 14 } catch (IndexOutOfBoundsException e) { 15 checkForComodification(); 16 throw new NoSuchElementException(); 17 } 18 } 19 public void remove() { 20 if (lastRet == -1) 21 throw new IllegalStateException(); 22 checkForComodification(); 23
24 try { 25 AbstractList.this.remove(lastRet); 26 if (lastRet < cursor) 27 cursor--; 28 lastRet = -1; 29 expectedModCount = modCount; 30 } catch (IndexOutOfBoundsException e) { 31 throw new ConcurrentModificationException(); 32 } 33 } 34
35 final void checkForComodification() { 36 if (modCount != expectedModCount) 37 throw new ConcurrentModificationException(); 38 } 39 }
首先咱們看一下它的幾個成員變量:
cursor:表示下一個要訪問的元素的索引,從next()方法的具體實現就可看出
lastRet:表示上一個訪問的元素的索引
expectedModCount:表示對ArrayList修改次數的指望值,它的初始值爲modCount。
modCount是AbstractList類中的一個成員變量
protected transient int modCount = 0;
該值表示對List的修改次數,查看ArrayList的add()和remove()方法就能夠發現,每次調用add()方法或者remove()方法就會對modCount進行加1操做。
好了,到這裏咱們再看看上面的程序:
當調用list.iterator()返回一個Iterator以後,經過Iterator的hashNext()方法判斷是否還有元素未被訪問,咱們看一下hasNext()方法,hashNext()方法的實現很簡單:
public boolean hasNext() { return cursor != size(); }
若是下一個訪問的元素下標不等於ArrayList的大小,就表示有元素須要訪問,這個很容易理解,若是下一個訪問元素的下標等於ArrayList的大小,則確定到達末尾了。
而後經過Iterator的next()方法獲取到下標爲0的元素,咱們看一下next()方法的具體實現:
public E next() { checkForComodification(); try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } }
這裏是很是關鍵的地方:首先在next()方法中會調用checkForComodification()方法,而後根據cursor的值獲取到元素,接着將cursor的值賦給lastRet,並對cursor的值進行加1操做。初始時,cursor爲0,lastRet爲-1,那麼調用一次以後,cursor的值爲1,lastRet的值爲0。注意此時,modCount爲0,expectedModCount也爲0。
接着往下看,程序中判斷當前元素的值是否爲2,若爲2,則調用list.remove()方法來刪除該元素。
咱們看一下在ArrayList中的remove()方法作了什麼:
public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work
}
經過remove方法刪除元素最終是調用的fastRemove()方法,在fastRemove()方法中,首先對modCount進行加1操做(由於對集合修改了一次),而後接下來就是刪除元素的操做,最後將size進行減1操做,並將引用置爲null以方便垃圾收集器進行回收工做。
那麼注意此時各個變量的值:對於iterator,其expectedModCount爲0,cursor的值爲1,lastRet的值爲0。
對於list,其modCount爲1,size爲0。
接着看程序代碼,執行完刪除操做後,繼續while循環,調用hasNext方法()判斷,因爲此時cursor爲1,而size爲0,那麼返回true,因此繼續執行while循環,而後繼續調用iterator的next()方法:
注意,此時要注意next()方法中的第一句:checkForComodification()。
在checkForComodification方法中進行的操做是:
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }
若是modCount不等於expectedModCount,則拋出ConcurrentModificationException異常。
很顯然,此時modCount爲1,而expectedModCount爲0,所以程序就拋出了ConcurrentModificationException異常。
到這裏,想必你們應該明白爲什麼上述代碼會拋出ConcurrentModificationException異常了。
關鍵點就在於:調用list.remove()方法致使modCount和expectedModCount的值不一致。
注意,像使用for-each進行迭代實際上也會出現這種問題。
既然知道緣由了,那麼如何解決呢?
其實很簡單,細心的朋友可能發如今Itr類中也給出了一個remove()方法:
1 public void remove() { 2 if (lastRet == -1) 3 throw new IllegalStateException(); 4 checkForComodification(); 5
6 try { 7 AbstractList.this.remove(lastRet); 8 if (lastRet < cursor) 9 cursor--; 10 lastRet = -1; 11 expectedModCount = modCount; 12 } catch (IndexOutOfBoundsException e) { 13 throw new ConcurrentModificationException(); 14 } 15 }
在這個方法中,刪除元素實際上調用的就是list.remove()方法,可是它多了一個操做:
expectedModCount = modCount;
所以,在迭代器中若是要刪除元素的話,須要調用Itr類的remove方法。
將上述代碼改成下面這樣就不會報錯了:
public class Test { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(2); Iterator<Integer> iterator = list.iterator(); while(iterator.hasNext()){ Integer integer = iterator.next(); if(integer==2) iterator.remove(); //注意這個地方
} } }
上面的解決辦法在單線程環境下適用,可是在多線程下適用嗎?看下面一個例子:
1 public class Test { 2 static ArrayList<Integer> list = new ArrayList<Integer>(); 3 public static void main(String[] args) { 4 list.add(1); 5 list.add(2); 6 list.add(3); 7 list.add(4); 8 list.add(5); 9 Thread thread1 = new Thread(){ 10 public void run() { 11 Iterator<Integer> iterator = list.iterator(); 12 while(iterator.hasNext()){ 13 Integer integer = iterator.next(); 14 System.out.println(integer); 15 try { 16 Thread.sleep(100); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 } 21 }; 22 }; 23 Thread thread2 = new Thread(){ 24 public void run() { 25 Iterator<Integer> iterator = list.iterator(); 26 while(iterator.hasNext()){ 27 Integer integer = iterator.next(); 28 if(integer==2) 29 iterator.remove(); 30 } 31 }; 32 }; 33 thread1.start(); 34 thread2.start(); 35 } 36 }
運行結果:
有可能有朋友說ArrayList是非線程安全的容器,換成Vector就沒問題了,實際上換成Vector仍是會出現這種錯誤。
緣由在於,雖然Vector的方法採用了synchronized進行了同步,可是因爲Vector是繼承的AbstarctList,所以經過Iterator來訪問容器的話,事實上是不須要獲取鎖就能夠訪問。那麼顯然,因爲使用iterator對容器進行訪問不須要獲取鎖,在多線程中就會形成當一個線程刪除了元素,因爲modCount是AbstarctList的成員變量,所以可能會致使在其餘線程中modCount和expectedModCount值不等。
就好比上面的代碼中,很顯然iterator是線程私有的,
初始時,線程1和線程2中的modCount、expectedModCount都爲0,
當線程2經過iterator.remove()刪除元素時,會修改modCount值爲1,而且會修改線程2中的expectedModCount的值爲1,
而此時線程1中的expectedModCount值爲0,雖然modCount不是volatile變量,不保證線程1必定看獲得線程2修改後的modCount的值,可是也有可能看獲得線程2對modCount的修改,這樣就有可能致使線程1中比較expectedModCount和modCount不等,而拋出異常。
所以通常有2種解決辦法:
1)在使用iterator迭代的時候使用synchronized或者Lock進行同步;
2)使用併發容器CopyOnWriteArrayList代替ArrayList和Vector。
關於併發容器的內容將在下一篇文章中講述。
參考資料: