轉(zhuǎn)載D美ⅰ6掏伞氢架!? ??andy.zhou的博客園原文? ?感謝!E竽А岖研!
個人學(xué)習(xí)使用,為方便私人整理查看而搬運(yùn)铺厨,侵權(quán)即刪缎玫。
目錄
一.ConcurrentModificationException異常出現(xiàn)的原因
轉(zhuǎn)載:?Java ConcurrentModificationException異常原因和解決方法
對Vector、ArrayList在迭代的時候如果同時對其進(jìn)行修改就會拋出java.util.ConcurrentModificationException異常解滓。下面討論這個異常出現(xiàn)的原因以及解決辦法赃磨。
一.ConcurrentModificationException異常出現(xiàn)的原因
先看下面這段代碼:
publicclassTest{publicstaticvoidmain(String[] args){? ? ? ?
?ArrayList list =newArrayList();? ? ? ?
?list.add(2);? ? ??
? Iterator iterator = list.iterator();
while(iterator.hasNext()){? ? ? ?
?? ? Integer integer = iterator.next();
if(integer==2)? ? ? ? ? ? ? ?
?list.remove(integer);? ? ?
?? }? ? }}
運(yùn)行結(jié)果:
從異常信息可以發(fā)現(xiàn),異常出現(xiàn)在checkForComodification()方法中洼裤。
我們不忙看checkForComodification()方法的具體實現(xiàn)邻辉,我們先根據(jù)程序的代碼一步一步看ArrayList源碼的實現(xiàn):
首先看ArrayList的iterator()方法的具體實現(xiàn),查看源碼發(fā)現(xiàn)在ArrayList的源碼中并沒有iterator()這個方法腮鞍,那么很顯然這個方法應(yīng)該是其父類或者實現(xiàn)的接口中的方法值骇,我們在其父類AbstractList中找到了iterator()方法的具體實現(xiàn),下面是其實現(xiàn)代碼:
publicIteratoriterator(){returnnewItr();}
從這段代碼可以看出返回的是一個指向Itr類型對象的引用移国,我們接著看Itr的具體實現(xiàn)吱瘩,在AbstractList類中找到了Itr類的具體實現(xiàn),它是AbstractList的一個成員內(nèi)部類迹缀,下面這段代碼是Itr類的所有實現(xiàn):
privateclassItrimplementsIterator{intcursor =0;intlastRet = -1;intexpectedModCount = modCount;publicbooleanhasNext(){returncursor != size();? ? }publicEnext(){? ? ? ? ? checkForComodification();try{? ? ? ? E next = get(cursor);? ? ? ? lastRet = cursor++;returnnext;? ? ? ? }catch(IndexOutOfBoundsException e) {? ? ? ? checkForComodification();thrownewNoSuchElementException();? ? ? ? }? ? }publicvoidremove(){if(lastRet == -1)thrownewIllegalStateException();? ? ? ? ? checkForComodification();try{? ? ? ? AbstractList.this.remove(lastRet);if(lastRet < cursor)? ? ? ? ? ? cursor--;? ? ? ? lastRet = -1;? ? ? ? expectedModCount = modCount;? ? ? ? }catch(IndexOutOfBoundsException e) {thrownewConcurrentModificationException();? ? ? ? }? ? }finalvoidcheckForComodification(){if(modCount != expectedModCount)thrownewConcurrentModificationException();? ? }}
首先我們看一下它的幾個成員變量:
cursor:表示下一個要訪問的元素的索引使碾,從next()方法的具體實現(xiàn)就可看出
lastRet:表示上一個訪問的元素的索引
expectedModCount:表示對ArrayList修改次數(shù)的期望值蜜徽,它的初始值為modCount。
modCount是AbstractList類中的一個成員變量
protectedtransientintmodCount =0;
該值表示對List的修改次數(shù)票摇,查看ArrayList的add()和remove()方法就可以發(fā)現(xiàn)拘鞋,每次調(diào)用add()方法或者remove()方法就會對modCount進(jìn)行加1操作。
好了矢门,到這里我們再看看上面的程序:
當(dāng)調(diào)用list.iterator()返回一個Iterator之后盆色,通過Iterator的hashNext()方法判斷是否還有元素未被訪問,我們看一下hasNext()方法祟剔,hashNext()方法的實現(xiàn)很簡單:
publicbooleanhasNext(){returncursor != size();}
如果下一個訪問的元素下標(biāo)不等于ArrayList的大小隔躲,就表示有元素需要訪問,這個很容易理解峡扩,如果下一個訪問元素的下標(biāo)等于ArrayList的大小蹭越,則肯定到達(dá)末尾了。
然后通過Iterator的next()方法獲取到下標(biāo)為0的元素教届,我們看一下next()方法的具體實現(xiàn):
publicEnext(){??
?checkForComodification();
try{? ? E next = get(cursor);? ?
?lastRet = cursor++;returnnext;
?}catch(IndexOutOfBoundsException e) {??
? checkForComodification();
thrownewNoSuchElementException(); }}
這里是非常關(guān)鍵的地方:首先在next()方法中會調(diào)用checkForComodification()方法响鹃,然后根據(jù)cursor的值獲取到元素,接著將cursor的值賦給lastRet案训,并對cursor的值進(jìn)行加1操作买置。初始時,cursor為0强霎,lastRet為-1忿项,那么調(diào)用一次之后,cursor的值為1城舞,lastRet的值為0轩触。注意此時,modCount為0家夺,expectedModCount也為0脱柱。
接著往下看,程序中判斷當(dāng)前元素的值是否為2拉馋,若為2榨为,則調(diào)用list.remove()方法來刪除該元素。
我們看一下在ArrayList中的remove()方法做了什么:
publicbooleanremove(Object o){
if(o ==null) {
for(intindex =0; index < size; index++)
if(elementData[index] ==null) {? ? ? ? ??
? ? ? fastRemove(index);returntrue;
? ? ? ? ? ? }? ? }else{for(intindex =0; index < size; index++)
if(o.equals(elementData[index])) {
? ? ? ? ? ? ? ? fastRemove(index);returntrue;
? ? ? ? ? ? }? ? }returnfalse;}privatevoidfastRemove(intindex){?
?? modCount++;intnumMoved = size - index -1;if(numMoved >0)?
?? ? ? System.arraycopy(elementData, index+1, elementData, index,? numMoved);?
?? elementData[--size] =null;// Let gc do its work
}
通過remove方法刪除元素最終是調(diào)用的fastRemove()方法煌茴,在fastRemove()方法中随闺,首先對modCount進(jìn)行加1操作(因為對集合修改了一次),然后接下來就是刪除元素的操作蔓腐,最后將size進(jìn)行減1操作矩乐,并將引用置為null以方便垃圾收集器進(jìn)行回收工作。
那么注意此時各個變量的值:對于iterator回论,其expectedModCount為0绰精,cursor的值為1撒璧,lastRet的值為0透葛。
對于list笨使,其modCount為1,size為0僚害。
接著看程序代碼硫椰,執(zhí)行完刪除操作后,繼續(xù)while循環(huán)萨蚕,調(diào)用hasNext方法()判斷靶草,由于此時cursor為1,而size為0岳遥,那么返回true奕翔,所以繼續(xù)執(zhí)行while循環(huán),然后繼續(xù)調(diào)用iterator的next()方法:
注意浩蓉,此時要注意next()方法中的第一句:checkForComodification()派继。
在checkForComodification方法中進(jìn)行的操作是:
finalvoidcheckForComodification(){if(modCount != expectedModCount)thrownewConcurrentModificationException();}
如果modCount不等于expectedModCount,則拋出ConcurrentModificationException異常捻艳。
很顯然驾窟,此時modCount為1,而expectedModCount為0认轨,因此程序就拋出了ConcurrentModificationException異常绅络。
到這里,想必大家應(yīng)該明白為何上述代碼會拋出ConcurrentModificationException異常了嘁字。
關(guān)鍵點(diǎn)就在于:調(diào)用list.remove()方法導(dǎo)致modCount和expectedModCount的值不一致恩急。
注意,像使用for-each進(jìn)行迭代實際上也會出現(xiàn)這種問題纪蜒。
二.在單線程環(huán)境下的解決辦法
既然知道原因了衷恭,那么如何解決呢?
其實很簡單霍掺,細(xì)心的朋友可能發(fā)現(xiàn)在Itr類中也給出了一個remove()方法:
publicvoidremove(){if(lastRet == -1)thrownewIllegalStateException();? ? ? checkForComodification();try{? ? AbstractList.this.remove(lastRet);if(lastRet < cursor)? ? ? ? cursor--;? ? lastRet = -1;? ? expectedModCount = modCount;? ? }catch(IndexOutOfBoundsException e) {thrownewConcurrentModificationException();? ? }}
在這個方法中匾荆,刪除元素實際上調(diào)用的就是list.remove()方法,但是它多了一個操
expectedModCount = modCount;
因此杆烁,在迭代器中如果要刪除元素的話牙丽,需要調(diào)用Itr類的remove方法。
將上述代碼改為下面這樣就不會報錯了:
publicclassTest{publicstaticvoidmain(String[] args){? ? ? ? ArrayList list =newArrayList();? ? ? ? list.add(2);? ? ? ? Iterator iterator = list.iterator();while(iterator.hasNext()){? ? ? ? ? ? Integer integer = iterator.next();if(integer==2)? ? ? ? ? ? ? ? iterator.remove();//注意這個地方}? ? }}
三.在多線程環(huán)境下的解決方法
上面的解決辦法在單線程環(huán)境下適用兔魂,但是在多線程下適用嗎烤芦?看下面一個例子:
publicclassTest{staticArrayList list =newArrayList();publicstaticvoidmain(String[] args){? ? ? ? list.add(1);? ? ? ? list.add(2);? ? ? ? list.add(3);? ? ? ? list.add(4);? ? ? ? list.add(5);? ? ? ? Thread thread1 =newThread(){publicvoidrun(){? ? ? ? ? ? ? ? Iterator iterator = list.iterator();while(iterator.hasNext()){? ? ? ? ? ? ? ? ? ? Integer integer = iterator.next();? ? ? ? ? ? ? ? ? ? System.out.println(integer);try{? ? ? ? ? ? ? ? ? ? ? ? Thread.sleep(100);? ? ? ? ? ? ? ? ? ? }catch(InterruptedException e) {? ? ? ? ? ? ? ? ? ? ? ? e.printStackTrace();? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? }? ? ? ? ? ? };? ? ? ? };? ? ? ? Thread thread2 =newThread(){publicvoidrun(){? ? ? ? ? ? ? ? Iterator iterator = list.iterator();while(iterator.hasNext()){? ? ? ? ? ? ? ? ? ? Integer integer = iterator.next();if(integer==2)? ? ? ? ? ? ? ? ? ? ? ? iterator.remove();? ? ? ? ? ? ? ? }? ? ? ? ? ? };? ? ? ? };? ? ? ? thread1.start();? ? ? ? thread2.start();? ? }}
運(yùn)行結(jié)果:
有可能有朋友說ArrayList是非線程安全的容器,換成Vector就沒問題了析校,實際上換成Vector還是會出現(xiàn)這種錯誤构罗。
原因在于铜涉,雖然Vector的方法采用了synchronized進(jìn)行了同步,但是由于Vector是繼承的AbstarctList遂唧,因此通過Iterator來訪問容器的話芙代,事實上是不需要獲取鎖就可以訪問。那么顯然盖彭,由于使用iterator對容器進(jìn)行訪問不需要獲取鎖纹烹,在多線程中就會造成當(dāng)一個線程刪除了元素,由于modCount是AbstarctList的成員變量召边,因此可能會導(dǎo)致在其他線程中modCount和expectedModCount值不等铺呵。
就比如上面的代碼中,很顯然iterator是線程私有的隧熙,
初始時片挂,線程1和線程2中的modCount、expectedModCount都為0贞盯,
當(dāng)線程2通過iterator.remove()刪除元素時音念,會修改modCount值為1,并且會修改線程2中的expectedModCount的值為1邻悬,
而此時線程1中的expectedModCount值為0症昏,雖然modCount不是volatile變量,不保證線程1一定看得到線程2修改后的modCount的值父丰,但是也有可能看得到線程2對modCount的修改肝谭,這樣就有可能導(dǎo)致線程1中比較expectedModCount和modCount不等,而拋出異常蛾扇。
因此一般有2種解決辦法:
1)在使用iterator迭代的時候使用synchronized或者Lock進(jìn)行同步攘烛;
2)使用并發(fā)容器CopyOnWriteArrayList代替ArrayList和Vector。
關(guān)于并發(fā)容器的內(nèi)容將在下一篇文章中講述镀首。
參考資料: