大家應該都知道, 在Java中, 在對一些集合迭代的過程中對集合進行一些修改的操作, 比如說add,remove之類的操作, 搞不好就會拋ConcurrentModificationException, 這一點在API文檔上也有說的! 在迭代時只可以用迭代器進行刪除!
但是文檔上只是說了刪除, 其他操作也會引起ConcurrentModificationException, 這是為何呢.? 下面就跟著我一起探索源代碼吧! 就以ArrayList為例!
當我在迭代ArrayList時, 首先獲取ArrayList的迭代器ArrayList.iterator(), 接下來就是hasNext與next的使用,例如:
List list = new ArrayList();
list.add("a");
list.add("b");
for(Iterator it = list.iterator(); it.hasNext;) {
Object o = it.next();
}
但是如果你在迭代的過程中不是用迭代器對集合進行修改, 而是用直接操作集合, 例如在迭代中: list.add(c);
此時你就非常有可能會慘兮兮了, 為什么只是有可能而非絕對呢? 下面接著分析
跟進ArrayList的源碼看, 搜索iterator()方法看其獲得的迭代器, 發現沒有! 于是追其父類 AbstractList, iterator()方法返回new Itr()!
查看Itr中的兩個重要的方法: hasNext與next
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();
}
}
看next中調用的checkForComodification(), 在remove方法中也調用了checkForComodification()!接著checkForComodification()方法里面在做些什么事情!
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
所以在迭代的過程中,hasNext()是不會拋出ConcurrentModificationException的, next和remove可能方法會拋! 拋異常的標準就是modCount != expectedModCount!繼續跟蹤這兩個變量,在Itr類的成員變量里對expectedModCount初始化的賦值是int expectedModCount = modCount;
那么這個modCount呢.? 這個是AbstractList中的一個protected的變量, 在對集合增刪的操作中均對modCount做了修改, 因為這里是拿ArrayList為例, 所以直接看ArrayList中有沒有覆蓋父類的add.? 結果發現覆蓋了
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
remove方法中也做了modCount++, 當我獲得迭代器之前, 無論對集合做了多少次添加刪除操作, 都沒有關系, 因為對expectedModCount賦值是在獲取迭代器的時候初始化的!
也就是說, 如果我對集合添加刪除一共操作了10次,此時modCount為10, 獲取迭代器的時候expectedModCount也為10, 迭代期間會去checkForComodification()! 只要在next或者remove之前有對集合操作的動作導致modCount發生了改變, 就會拋那個并發修改異常!
為什么上面的可能會異常呢? 當modCount發生改變時, hasNext返回false的時候, 就不會執行循環里面的next/remove方法了, 也就不會拋異常了!
例如集合現在只有一個元素, 先Object o = it.next(),然后list.remove(o); 此時modCount變了, 但是下次hasNext返回false, next就不會執行,所以此時是不會拋異常的!
所以大家以后迭代集合的同時對集合操作一定要小心又小心, 不要以為沒有拋異常就是沒事!
而且在多線程并發的時候, 一個線程要迭代, 一個線程要對集合操作的時候, 拋不拋異常就要撞大運了!
google上對怎么解決ConcurrentModificationException的方案已經很多, 例如用Collections.synchronizedCollection() 去同步集合, 但是這樣可能會影響效率, JDK5之后concurrent包里面有個CopyOnWriteArrayList, 這個集合迭代的時候可以對集合進行增刪操作, 因為迭代器中沒有checkForComodification!
但是好像沒看到有分析為什么的, 所以就寫了本文給大家分享下, 文中只拿ArrayList出來作為例子解釋了為何會拋ConcurrentModificationException以及如何從原理上去避免!集合的種類眾多, 各種迭代和集合操作的實現也不一樣, 例如我看到SubList的add方法中就有checkForComodification,而ArrayList沒有!
所以大家以后如果遇到ConcurrentModificationException的話, 拿著我寫的這個思路去舉一反三, 靜下心來找下源代碼都是可以解決問題的!