今天在修改程序的一個功能時叽唱,出現(xiàn)了ConcurrentModificationException異常励两,度娘之得到解答帕涌,本人轉(zhuǎn)載僅作為學習參考噩茄,轉(zhuǎn)載注明原文下面。
轉(zhuǎn)載自博客園Java ConcurrentModificationException異常原因和解決方法
功能類似于代碼片段所示,遍歷List绩聘,并且刪除特定的元素
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)
list.remove(integer);
}
}
}
運行結(jié)果:從異常信息可以發(fā)現(xiàn)沥割,異常出現(xiàn)在checkForComodification()方法中耗啦。
我們不忙看checkForComodification()方法的具體實現(xiàn),我們先根據(jù)程序的代碼一步一步看ArrayList源碼的實現(xiàn):
首先看ArrayList的iterator()方法的具體實現(xiàn)机杜,查看源碼發(fā)現(xiàn)在ArrayList的源碼中并沒有iterator()這個方法帜讲,那么很顯然這個方法應該是其父類或者實現(xiàn)的接口中的方法,我們在其父類AbstractList中找到了iterator()方法的具體實現(xiàn)椒拗,下面是其實現(xiàn)代碼:
public Iterator<E> iterator() {
return new Itr();
}
從這段代碼可以看出返回的是一個指向Itr類型對象的引用似将,我們接著看Itr的具體實現(xiàn),在AbstractList類中找到了Itr類的具體實現(xiàn)陡叠,它是AbstractList的一個成員內(nèi)部類玩郊,下面這段代碼是Itr類的所有實現(xiàn):
private class Itr implements Iterator<E> {
int cursor = 0;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
首先我們看一下它的幾個成員變量:
cursor:表示下一個要訪問的元素的索引,從next()方法的具體實現(xiàn)就可看出
lastRet:表示上一個訪問的元素的索引
expectedModCount:表示對ArrayList修改次數(shù)的期望值枉阵,它的初始值為modCount译红。
modCount是AbstractList類中的一個成員變量
protected transient int modCount = 0;
該值表示對List的修改次數(shù),查看ArrayList的add()和remove()方法就可以發(fā)現(xiàn)兴溜,每次調(diào)用add()方法或者remove()方法就會對modCount進行加1操作侦厚。
好了,到這里我們再看看上面的程序:
當調(diào)用list.iterator()返回一個Iterator之后拙徽,通過Iterator的hashNext()方法判斷是否還有元素未被訪問刨沦,我們看一下hasNext()方法,hashNext()方法的實現(xiàn)很簡單:
public boolean hasNext() {
return cursor != size();
}
如果下一個訪問的元素下標不等于ArrayList的大小膘怕,就表示有元素需要訪問想诅,這個很容易理解,如果下一個訪問元素的下標等于ArrayList的大小岛心,則肯定到達末尾了来破。
然后通過Iterator的next()方法獲取到下標為0的元素,我們看一下next()方法的具體實現(xiàn):
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
這里是非常關(guān)鍵的地方:首先在next()方法中會調(diào)用checkForComodification()方法忘古,然后根據(jù)cursor的值獲取到元素徘禁,接著將cursor的值賦給lastRet,并對cursor的值進行加1操作髓堪。初始時送朱,cursor為0,lastRet為-1干旁,那么調(diào)用一次之后驶沼,cursor的值為1,lastRet的值為0争群。注意此時商乎,modCount為0,expectedModCount也為0祭阀。
接著往下看鹉戚,程序中判斷當前元素的值是否為2,若為2专控,則調(diào)用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方法刪除元素最終是調(diào)用的fastRemove()方法,在fastRemove()方法中伦腐,首先對modCount進行加1操作(因為對集合修改了一次)赢底,然后接下來就是刪除元素的操作,最后將size進行減1操作柏蘑,并將引用置為null以方便垃圾收集器進行回收工作幸冻。
那么注意此時各個變量的值:對于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方法中進行的操作是:
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
如果modCount不等于expectedModCount劫哼,則拋出ConcurrentModificationException異常。
很顯然割笙,此時modCount為1权烧,而expectedModCount為0,因此程序就拋出了ConcurrentModificationException異常伤溉。
到這里般码,想必大家應該明白為何上述代碼會拋出ConcurrentModificationException異常了。
關(guān)鍵點就在于:調(diào)用list.remove()方法導致modCount和expectedModCount的值不一致乱顾。
注意板祝,像使用for-each進行迭代實際上也會出現(xiàn)這種問題。
單線程解決方案
既然知道原因了走净,那么如何解決呢券时?
其實很簡單孤里,細心的朋友可能發(fā)現(xiàn)在Itr類中也給出了一個remove()方法:
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
在這個方法中,刪除元素實際上調(diào)用的就是list.remove()方法橘洞,但是它多了一個操作:
expectedModCount = modCount;
因此捌袜,在迭代器中如果要刪除元素的話,需要調(diào)用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(); //注意這個地方
}
}
}
多線程解決方案請參考原文虏等。