集合并发修改异常

集合并发修改异常

先看例子
在对集合进行迭代器遍历时,在遍历过程中对集合中元素进行增加或删除,在删除数据之后会报并发修改异常。

原因:

在迭代过程中,不能修改集合结构。
我们采用 hasnext()方法判断集合是否还有元素可遍历,采用 next()方法获取元素。而 next()方法会每次检查集合结构是否发生变化。

1
2
3
4
5
6
7
8
9
10
11
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];
}

next()方法会在第一行调用 checkForComodification()方法检测集合结构是否发生变化。如果发生变化则会报异常。

1
2
3
4
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}

checkForComodification()方法会检查集合结构是否发生变化。
cursor 是下一次要取的元素下标,next()方法执行后,cursor 就会往后移动一下。
这里modCount是 ArrayList 继承自 AbstractList 的变量,用来记录集合元素个数发生变化(增加和删除)的次数。
expectedModCount是类 Itr 的变量,是迭代器记录集合元素个数变化的次数。如下图所示:

1
2
3
4
5
6
7
8
9
10
11
12
public Iterator<E> iterator() {
return new Itr();
}

/**
* An optimized version of AbstractList.Itr
*/
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;
Itr() {}

在调用 iterator()方法时会返回一个 Itr 类的对象,同时会创建变量 expectedModCount,并将 modCount 传递给它,此时这两个值相等。

1
2
3
4
5
6
7
8
9
10
11
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;
}
1
2
3
4
5
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
1
2
3
4
5
6
7
8
9
10
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}

而我们在对集合中添加或删除元素时,都会改变 modCount 的值,如上图所示:
当添加或删除这个操作在迭代过程中时,next()方法检查到 modCount 与 expectedModCount 值不一样,就会报并发修改异常。
那为什么迭代器自己的方法不会报异常?如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();
}
}

我们发现迭代器自己的 remove()方法底层还是调用集合的 remove()方法,但比集合的 remove()方法多了一个在删除过后修改 expectedModCount 变量的过程。
使得删除后 expectedModCount 和 modCount 的值相同,这样在下一次 next()方法时,就不会报异常。
并发修改异常的意义在于保证迭代器获取到正确的元素。

解决办法:

1、在迭代器中不使用集合的增加删除操作。修改操作没有影响(修改操作不会改变集合元素的个数)。
2、当需要在迭代过程中需要对集合增加元素时,可是采用 Iterator 的子类 ListIterator,采用 listIterator()方法,该方法会返回一个 ListItr 类(仅支持 List)的对象,该类提供了反向遍历及增加的方法。

其他:

1、当 next()方法获取到的是集合的倒数第二个元素的时候,使用集合的删除操作不会发生异常

此时是因为:
当遍历到倒数第二个元素时,此时 cursor 的值为 size-1(倒数第二个元素的下标索引为 size-2,next()方法执行后 cursor 会加 1),而在此时进行删除操作后,size 的值会减一,变的和 cursor 相同。

1
2
3
public boolean hasNext() {
return cursor != SubList.this.size;
}

程序继续执行,hasnext()方法判断 cursor 和 size 相同,会返回 false,集合遍历将会终止。
2、在 foreach 循环遍历集合时中也不能采用集合的增加删除方法。因为 foreach 循环底层也是通过迭代器进行遍历,如果修改,同样会报异常。
3、
**