for (Order order:doneOrders) {
if (comment.getCommentOrderId().equals(doneOrders.get(i).getOrderId())){
doneOrders.remove(i);
}else {
i++;
}
}
以上代码抛出了ConcurrentModificationExpection
为什么?
原因是在使用迭代器循环遍历ArrayList时, 在循环中使用了ArrayList.remove() 移除元素。
@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];
}
final void checkForComodification() {
if (modCount != expectedModCount) //expectedModCount是Itr的成员变量
throw new ConcurrentModificationException();
}
在ArrayList中有一个私有内部类Itr (文末有jdk1.8 的 Itr源码),它实现了Iterator接口,在迭代list时,会循环执行next()方法,在next方法体中第一行,调用了checkForComodification方法。
在 checkForComodification 方法中可以看到,如果 modCount 不等于 expectedModCount,抛出异常。所以现在只需要知道,modCount 和 expectedModCount 各自是什么意思,就能明白为什么抛出异常。
expectedModCount:fail-fast(快速失败)判断的关键变量,它初始值就为ArrayList中的modCount。
modCount
ArrayList 类继承了 AbstractList 类
在AbstractList 类中定义了一个成员变量 modCount (该list的尺寸被修改的次数) 初始值为0
//ArrayList 中的remove 方法
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;
}
由上面代码可看出,ArrayList 在调用自己的remove 方法移除元素时,会将modCount +1
然而在迭代器循环变量 arrayList 时,使用的next方法, next方法体的第一行,调用了checkForComodification() 方法,检查modCount 与 expectedModCount 是否一致,如果不一致则抛出ConcurrentModificationExpection (在对一个集合对象进行迭代操作的同时,并不限制对集合对象的元素进行操作 这些操作包括一些可能引起迭代错误的add()或remove()等危险操作。以防后面还没有被遍历到的元素可能被修改?)
如何避免?
1、单线程情况下,在使用迭代器循环变量时,可以使用ArrayList 私有内部类 Itr 的remove 方法,
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();
}
}
它的核心代码虽然还是ArrayList 的remove方法,会使modCount+1
但他在下面对 游标cursor ,lastRet ,exprctedModCount 进行了重新赋值,使得遍历下个元素调用next方法并调用checkForComodification() 方法时,不会抛出异常。
2、单线程情况下,使用for循环,遍历集合
List<Integer> list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
for (int i = 0; i < list.size(); i++) {
if (i == 1){
list.remove(i);
}
}
3、多线程情况下,使用CopyOnWriteArrayList,替换ArrayList。
CopyOnWriteArrayList内部的迭代方法没有 checkForComodification()。 但CopyOnWriteArrayList保证的是最终一致性,不能保证数据的实时一致性。
这是因为CopyOnWriteArrayList在写时其实是将原数组复制一份,在新数组中修改,再把原数组的调用指向新数组。写的过程是加锁的,否则多个线程修改list会copy出多个版本。
在读时,如果有多个线程在修改list,依旧只能读到旧的原数组,其他线程对新数组的修改影响不到读取。
public E next() {
if (! hasNext())
throw new NoSuchElementException();
return (E) snapshot[cursor++];
}
以下为ArrayList 私有内部类 Itr 的源码
cursor是指集合遍历过程中的即将遍历的元素的索引,lastRet是cursor -1,默认为-1,即不存在上一个时,为-1,它主要用于记录刚刚遍历过的元素的索引。expectedModCount这个就是fail-fast(快速失败)判断的关键变量,它初始值就为ArrayList中的modCount。
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();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}