Java 提供了一個(gè) Iterable 接口返回一個(gè)迭代器武契,常用的 Collection<E>肘迎、List<E>、Set<E> 等都實(shí)現(xiàn)了這個(gè)接口,該接口的 iterator() 方法返回一個(gè)標(biāo)準(zhǔn)的 Iterator 實(shí)現(xiàn),實(shí)現(xiàn) Iterable 接口允許對(duì)象成為 for-each 語(yǔ)句的目標(biāo)來(lái)遍歷底層集合序列迅办,因此使用 for-each 方式遍歷列表在編譯后實(shí)質(zhì)是迭代器的形式實(shí)現(xiàn)。之所以會(huì)出現(xiàn) ConcurrentModificationException 異常我們需要去看下最常見(jiàn)的 ArrayList 中 iterator() 方法的實(shí)現(xiàn)(別的集合 iterator 類(lèi)似)章蚣,如下:
public class Itr implements Iterator<E> {
protected int limit = ArrayList.this.size; //集合列表的個(gè)數(shù)尺寸
int cursor; //下一個(gè)元素的索引位置
int lastRet = -1; //上一個(gè)元素的索引位置
int expectedModCount = modCount;
@Override
public boolean hasNext() {
return cursor < limit;
}
@Override
public E next() {
// modCount用于記錄ArrayList集合的修改次數(shù)站欺,初始化為0,
// 每當(dāng)集合被修改一次(結(jié)構(gòu)上面的修改纤垂,內(nèi)部update不算)矾策,
// 如add、remove等方法峭沦,modCount + 1贾虽,所以如果modCount不變,
// 則表示集合內(nèi)容沒(méi)有被修改吼鱼。
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
int i = cursor;
//如果下一個(gè)元素的索引位置超過(guò)了集合長(zhǎng)度拋出異常
if (i >= limit) {
throw new NoSuchElementException();
}
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
// 調(diào)用一次cursor加一次
cursor = i + 1;
//返回當(dāng)前一個(gè)元素
return (E) elementData[lastRet = i];
}
@Override
public void remove() {
// lastRet每次在remove成功后都需要在next()中重新賦值蓬豁,
// 否則調(diào)用一次后再調(diào)用為-1異常,因此使用迭代器的remove方法
// 前必須先調(diào)用next()方法菇肃。
if (lastRet < 0) {
throw new IllegalStateException();
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
limit--;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
......
}
通過(guò)上面的源碼發(fā)現(xiàn)迭代操作中都有判斷 modCount != expectedModCount的操作地粪,在 ArrayList 中 modCount 是當(dāng)前集合的版本號(hào),每次修改(增琐谤、刪)集合都會(huì)加 1蟆技,expectedModCount 是當(dāng)前迭代器的版本號(hào),在迭代器實(shí)例化時(shí)初始化為 modCount斗忌,所以當(dāng)調(diào)用 ArrayList.add() 或 ArrayList.remove() 時(shí)只是更新了 modCount 的狀態(tài)质礼,而迭代器中的 expectedModCount 未修改,因此才會(huì)導(dǎo)致再次調(diào)用 Iterator.next() 方法時(shí)拋出 ConcurrentModificationException 異常织阳。而使用 Iterator.remove() 方法沒(méi)有問(wèn)題是因?yàn)?Iterator 的 remove() 方法中有同步 expectedModCount 值眶蕉,所以當(dāng)下次再調(diào)用 next() 時(shí)檢查不會(huì)拋出異常。這其實(shí)是一種快速失敗機(jī)制唧躲,機(jī)制的規(guī)則就是當(dāng)多個(gè)線程對(duì) Collection 進(jìn)行操作時(shí)若其中某一個(gè)線程通過(guò) Iterator 遍歷集合時(shí)該集合的內(nèi)容被其他線程所改變造挽,則拋出 ConcurrentModificationException 異常。
因此在使用 Iterator 遍歷操作集合時(shí)應(yīng)該保證在遍歷集合的過(guò)程中不會(huì)對(duì)集合產(chǎn)生結(jié)構(gòu)上的修改惊窖,如果在遍歷過(guò)程中需要修改集合元素則一定要使用迭代器提供的修改方法而不是集合自身的修改方法刽宪。此外, for-each 循環(huán)遍歷編譯后實(shí)質(zhì)會(huì)替換為迭代器實(shí)現(xiàn)界酒,使用迭代器的 remove() 方法前必須先調(diào)用迭代器的 next() 方法且不允許調(diào)用一次 next() 方法后調(diào)用多次 remove() 方法圣拄。