【轉(zhuǎn)自】http://www.cnblogs.com/dolphin0520/(作者:海子)
在前面一篇文章中提到延窜,對(duì)Vector昼浦、ArrayList在迭代的時(shí)候如果同時(shí)對(duì)其進(jìn)行修改就會(huì)拋出java.util.ConcurrentModificationException異常概荷。下面我們就來(lái)討論以下這個(gè)異常出現(xiàn)的原因以及解決辦法币旧。
以下是本文目錄大綱:
一.ConcurrentModificationException異常出現(xiàn)的原因
二.在單線程環(huán)境下的解決辦法
三.在多線程環(huán)境下的解決方法
若有不正之處請(qǐng)多多諒解晶姊,并歡迎批評(píng)指正
請(qǐng)尊重作者勞動(dòng)成果表锻,轉(zhuǎn)載請(qǐng)標(biāo)明原文鏈接:
http://www.cnblogs.com/dolphin0520/p/3933551.html
一.ConcurrentModificationException異常出現(xiàn)的原因
先看下面這段代碼:
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);
}
}
}
運(yùn)行結(jié)果:
從異常信息可以發(fā)現(xiàn)精钮,異常出現(xiàn)在checkForComodification()方法中威鹿。
我們不忙看checkForComodification()方法的具體實(shí)現(xiàn),我們先根據(jù)程序的代碼一步一步看ArrayList源碼的實(shí)現(xiàn):
首先看ArrayList的iterator()方法的具體實(shí)現(xiàn)轨香,查看源碼發(fā)現(xiàn)在ArrayList的源碼中并沒(méi)有iterator()這個(gè)方法忽你,那么很顯然這個(gè)方法應(yīng)該是其父類(lèi)或者實(shí)現(xiàn)的接口中的方法,我們?cè)谄涓割?lèi)AbstractList中找到了iterator()方法的具體實(shí)現(xiàn)臂容,下面是其實(shí)現(xiàn)代碼:
public Iterator<E> iterator() {
return new Itr();
}
從這段代碼可以看出返回的是一個(gè)指向Itr類(lèi)型對(duì)象的引用科雳,我們接著看Itr的具體實(shí)現(xiàn),在AbstractList類(lèi)中找到了Itr類(lèi)的具體實(shí)現(xiàn)脓杉,它是AbstractList的一個(gè)成員內(nèi)部類(lèi)糟秘,下面這段代碼是Itr類(lèi)的所有實(shí)現(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 {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet < 0)
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();
}
}
首先我們看一下它的幾個(gè)成員變量:
cursor:表示下一個(gè)要訪問(wèn)的元素的索引,從next()方法的具體實(shí)現(xiàn)就可看出
lastRet:表示上一個(gè)訪問(wèn)的元素的索引
expectedModCount:表示對(duì)ArrayList修改次數(shù)的期望值球散,它的初始值為modCount尿赚。
modCount是AbstractList類(lèi)中的一個(gè)成員變量
protected transient int modCount = 0;
該值表示對(duì)List的修改次數(shù),查看ArrayList的add()和remove()方法就可以發(fā)現(xiàn)蕉堰,每次調(diào)用add()方法或者remove()方法就會(huì)對(duì)modCount進(jìn)行加1操作凌净。
好了,到這里我們?cè)倏纯瓷厦娴某绦颍?/p>
當(dāng)調(diào)用list.iterator()返回一個(gè)Iterator之后屋讶,通過(guò)Iterator的hashNext()方法判斷是否還有元素未被訪問(wèn)冰寻,我們看一下hasNext()方法,hashNext()方法的實(shí)現(xiàn)很簡(jiǎn)單:
public boolean hasNext() {
return cursor != size();
}
如果下一個(gè)訪問(wèn)的元素下標(biāo)不等于ArrayList的大小丑婿,就表示有元素需要訪問(wèn)性雄,這個(gè)很容易理解,如果下一個(gè)訪問(wèn)元素的下標(biāo)等于ArrayList的大小羹奉,則肯定到達(dá)末尾了秒旋。
然后通過(guò)Iterator的next()方法獲取到下標(biāo)為0的元素,我們看一下next()方法的具體實(shí)現(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()方法中會(huì)調(diào)用checkForComodification()方法诀拭,然后根據(jù)cursor的值獲取到元素迁筛,接著將cursor的值賦給lastRet,并對(duì)cursor的值進(jìn)行加1操作耕挨。初始時(shí)细卧,cursor為0,lastRet為-1筒占,那么調(diào)用一次之后贪庙,cursor的值為1,lastRet的值為0翰苫。注意此時(shí)止邮,modCount為0这橙,expectedModCount也為0。
接著往下看导披,程序中判斷當(dāng)前元素的值是否為2屈扎,若為2,則調(diào)用list.remove()方法來(lái)刪除該元素撩匕。
我們看一下在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; // clear to let GC do its work
}
通過(guò)remove方法刪除元素最終是調(diào)用的fastRemove()方法鹰晨,在fastRemove()方法中,首先對(duì)modCount進(jìn)行加1操作(因?yàn)閷?duì)集合修改了一次)止毕,然后接下來(lái)就是刪除元素的操作模蜡,最后將size進(jìn)行減1操作,并將引用置為null以方便垃圾收集器進(jìn)行回收工作滓技。
那么注意此時(shí)各個(gè)變量的值:對(duì)于iterator哩牍,其expectedModCount為0棚潦,cursor的值為1令漂,lastRet的值為0。
對(duì)于list丸边,其modCount為1叠必,size為0。
接著看程序代碼妹窖,執(zhí)行完刪除操作后纬朝,繼續(xù)while循環(huán),調(diào)用hasNext方法()判斷骄呼,由于此時(shí)cursor為1共苛,而size為0,那么返回true蜓萄,所以繼續(xù)執(zhí)行while循環(huán)隅茎,然后繼續(xù)調(diào)用iterator的next()方法:
注意,此時(shí)要注意next()方法中的第一句:checkForComodification()嫉沽。
在checkForComodification方法中進(jìn)行的操作是:
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
如果modCount不等于expectedModCount辟犀,則拋出ConcurrentModificationException異常。
很顯然绸硕,此時(shí)modCount為1堂竟,而expectedModCount為0,因此程序就拋出了ConcurrentModificationException異常玻佩。
到這里出嘹,想必大家應(yīng)該明白為何上述代碼會(huì)拋出ConcurrentModificationException異常了。
關(guān)鍵點(diǎn)就在于:調(diào)用list.remove()方法導(dǎo)致modCount和expectedModCount的值不一致咬崔。
注意税稼,像使用for-each進(jìn)行迭代實(shí)際上也會(huì)出現(xiàn)這種問(wèn)題。
二.在單線程環(huán)境下的解決辦法
既然知道原因了,那么如何解決呢娶聘?
其實(shí)很簡(jiǎn)單闻镶,細(xì)心的朋友可能發(fā)現(xiàn)在Itr類(lèi)中也給出了一個(gè)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();
}
}
在這個(gè)方法中,刪除元素實(shí)際上調(diào)用的就是list.remove()方法丸升,但是它多了一個(gè)操作:
expectedModCount = modCount;
因此铆农,在迭代器中如果要?jiǎng)h除元素的話,需要調(diào)用Itr類(lèi)的remove方法狡耻。
將上述代碼改為下面這樣就不會(huì)報(bào)錯(cuò)了:
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(); //注意這個(gè)地方
}
}
}
三.在多線程環(huán)境下的解決方法
上面的解決辦法在單線程環(huán)境下適用墩剖,但是在多線程下適用嗎?看下面一個(gè)例子:
public class Test {
static ArrayList<Integer> list = new ArrayList<Integer> ();
public static void main(String[]args) {
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
Thread thread1 = new Thread() {
public void run() {
Iterator<Integer> 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 = new Thread() {
public void run() {
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer integer = iterator.next();
if (integer == 2)
iterator.remove();
}
} ;
} ;
thread1.start();
thread2.start();
}
}
運(yùn)行結(jié)果:
有可能有朋友說(shuō)ArrayList是非線程安全的容器夷狰,換成Vector就沒(méi)問(wèn)題了岭皂,實(shí)際上換成Vector還是會(huì)出現(xiàn)這種錯(cuò)誤。
原因在于沼头,雖然Vector的方法采用了synchronized進(jìn)行了同步爷绘,但是實(shí)際上通過(guò)Iterator訪問(wèn)的情況下,每個(gè)線程里面返回的是不同的iterator进倍,也即是說(shuō)expectedModCount是每個(gè)線程私有土至。假若此時(shí)有2個(gè)線程,線程1在進(jìn)行遍歷猾昆,線程2在進(jìn)行修改陶因,那么很有可能導(dǎo)致線程2修改后導(dǎo)致Vector中的modCount自增了,線程2的expectedModCount也自增了垂蜗,但是線程1的expectedModCount沒(méi)有自增楷扬,此時(shí)線程1遍歷時(shí)就會(huì)出現(xiàn)expectedModCount不等于modCount的情況了。
因此一般有2種解決辦法:
1)在使用iterator迭代的時(shí)候使用synchronized或者Lock進(jìn)行同步贴见;
2)使用并發(fā)容器CopyOnWriteArrayList代替ArrayList和Vector烘苹。
關(guān)于并發(fā)容器的內(nèi)容將在下一篇文章中講述。