什么是ConcurrentModificationException
集合如ArrayList在迭代时进行修改则会报出ConcurrentModificationException异常
如何实现
首先看下modCount,这个值是在ArrayList创建的时候初始化为0,并且对集合进行更新操作(add,remove等)时不断递增,确保每次进行更新操作后modCount的值都是不一样的,下面是remove()的实现代码
protected transient int modCount = 0;
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
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
return oldValue;
}
现在来看迭代器时如何实现的
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
......
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
第4行:创建新的迭代器Itr对象时,迭代器对象本身内部有个expectedModCount,值为创建Itr对象时ArrayList的modCount
倒数一个方法:checkForComodification(), 当迭代器的expectedModCount和当前的ArrayList的modCount不一致时则会抛出ConcurrentModificationException异常。
checkForComodification()方法在next()有调用,也就是说,在迭代过程中,ArrayList有用remove()更新操作则会报错。
为什么会有ConcurrentModificationException
如一个集合list当前状态为:A,B,C,D,E
且迭代器遍历了A,B,C,下一次遍历是D,此时源码中第二行变量cursor的值为2。
如果此时使用list.remove(A)(注意这里指的是用list的remove()方法而不是迭代器方法),则集合状态为:B,C,D,E
如果此时再遍历下一个值,而下个遍历的游标cursor为3,则遍历的结果为E,也就是说整个过程遍历了A,B,C,E,
D却没有被遍历到。故在进行更新操作后应该进行报错处理。
如何在迭代中删除一个元素
继续看源码,迭代器Itr中有一个remove()方法,它删除的对象只是上一个被遍历的对象,也就是当前的cursor,也是就是说当遍历到C时,只能将C删除,因为它只是删除。同时主动设置
expectedModCount = modCount,避免了ConcurrentModificationException。
以上内容只是单纯分析了ArrayList的remove()操作,其它非线程安全类更新操作也会报该异常。
涉及多线程操作的集合应该使用并法包下面的集合类。