问题
目标:想要在循环遍历的过程中删除集合中的元素,但是运行代码的时候遇到了这么一个错: java.util.ConcurrentModificationException: null,也就是一个并发修改异常


原因
简单地说下原因,在我那个项目的代码中,遍历的方式是增强 for 循环,在底层使用的也是迭代器。
也就是说,是用Itr去遍历的,这个Itr是ArrayList实现的一个遍历接口、内部类。
但是我在删除的时候是通过ArrayList的remove方法去操作的,不是Itr内部的那个删除方法去操作的。
那么问题就来了:
ArrayList的remove方法修改的变量是继承自AbstractList的变量modCount;而Itr的remove方法修改的是自身的变量expectedModCount。这两个变量的作用都是记录修改次数的。
所以,在用ArrayList的remove方法进行删除操作以后,Itr里面的expectedModCount会与ArrayList的modCount进行比较,二者不相等,所以会抛错。

源码分析
这里我写了一个方便问题复现的代码:
import java.util.ArrayList;
class MyTest{
public static void main(String[] args){
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i=0; i<10; i++){
arr.add(i);
}
for(Integer i: arr){
if(i == 5){
arr.remove(i);
}
else{
System.out.println(i);
}
}
}
}
运行,然后看看报错:
C:\Users\hzy\Desktop>javac MyTest.java
C:\Users\hzy\Desktop>java MyTest
0
1
2
3
4
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1009)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:963)
at test.main(test.java:10)
ok,报错的是ArrayList.java里的Itr.next()和Itr.checkForComodification()。
这里的Itr是在ArrayList的内部类,实现了Iterator接口,用于遍历。
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
... ...
/**
* 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;
// prevent creating a synthetic constructor
Itr() {}
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
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
int i = cursor;
if (i < size) {
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
... ...
报错就是在Itr.next()中调用checkForComodification()以后产生的,在checkForComodification()函数中,判断了modCount和expectedModCount是否相等。如果不相等,就会抛出我们遇到的这个异常。
显然,我们的报错就是因为这两个变量不相等导致的。
... ...
@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)
throw new ConcurrentModificationException();
}
ok,那这两个变量是什么含义呢?
- modCount是modification count的缩写,也就是当前的ArrayList被修改的次数,这个变量是ArrayList继承自AbstractList的。
可以在IDE中,按住Ctrl键,然后鼠标点一下变量modCount,就可以跳转到定义它的地方了~ - expectedModCount是expected modification count的缩写,也就是期望被修改的次数,这个变量是在内部类Itr中定义的,初始时赋值为modCount。
ok,那为什么我们的写法会导致这两个变量不一致呢?
这里要注意的是,我遍历的时候调用的是Itr.next(),但是我在循环中删除元素时,用的是ArrayList.this.remove():
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
... ...
public boolean remove(Object o) {
final Object[] es = elementData;
final int size = this.size;
int i = 0;
found: {
if (o == null) {
for (; i < size; i++)
if (es[i] == null)
break found;
} else {
for (; i < size; i++)
if (o.equals(es[i]))
break found;
}
return false;
}
fastRemove(es, i);
return true;
}
private void fastRemove(Object[] es, int i) {
modCount++;
final int newSize;
if ((newSize = size - 1) > i)
System.arraycopy(es, i + 1, es, i, newSize - i);
es[size = newSize] = null;
}
... ...
remove()函数会调用fastRemove()函数,使得modCount的值自增1.
然而,for循环下一次调用Itr.next(),Itr.next()调用Itr.checkForComodification()时,会发现,modCount和expectedModCount两个值不相等!因为在这个删除操作的过程中没有对expectedModCount重新赋值,所以就抛出异常了。
解决方法
-
【推荐】改成Iterator的迭代方式,用内部类Itr的remove方法来删除,保证一致性:
package com.wanma.apps.tool; import java.util.ArrayList; import java.util.Iterator; public class MyTest { public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { arr.add(i); } Iterator<Integer> it = arr.iterator(); while (it.hasNext()) { Integer i = it.next(); if (i == 5) { it.remove(); } else { System.out.println(i); } } System.out.println(arr); } } -
每次删除的时候都让i减1
import java.util.ArrayList; class MyTest{ public static void main(String[] args){ ArrayList<Integer> arr = new ArrayList<Integer>(); for(int i=0; i<10; i++){ arr.add(i); } for(int i=0; i<arr.size(); i++){ if(i == 5){ arr.remove(i); i -= 1; } else{ System.out.println(i); } } } } -
倒序删除,先遍历一遍记录要删除的下标,然后从末尾开始删除
另,ArrayList 是一个查询为主的数据结构,底层是数组实现的,本身就不太适合修改频繁以及并发修改的场景。
对于频繁修改的,可以用LinkedList,对于线程安全的,可以用JUC的CopyOnWriteArrayList。
– 于2021.4.11修改(下面的内容都是18年写的了…
分析(18年)
最后在网上看了一下,才发现是循环的时候,进行了删除的操作,所以才会报错,原因在于: 迭代器的expectedModCount和modCount的值不一致;
我代码中的这个recruitList是个ArrayList,而且循环中是一个迭代器来进行迭代的(参考java forEach实现原理). 因此不妨去看一下它的iterator实现方法:

根据注释可以看到, 返回的是一个指向Itr类型对象的正确顺序的引用(@return an iterator over the elements in this list in proper sequence);
然后往下可以看到Itr这个内部类的实现:
由注释可以看到:
cursor是下一个返回的元素的下标;lastRet是最后一个返回的元素的索引下标;expectedModCount:是对ArrayList修改次数的预期的数值,被初始化为modCount; 注意,这里expectedModCount是内部类 Itr 中的变量,而modCount是ArrayList继承自AbstractList的一个成员变量- 在这个内部类的末尾我看到了,
if (modCount != expectedModCount) throw new ConcurrentModificationException();看来这就是问题所在,只是这个modCount是什么呢?
/**
* 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() {}
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();
}
}
在ArrayList.java里ctrl 点一下 modCount找一下,发现modCount是ArrayList继承自AbstractList的一个成员变量, 表示对List的修改次数,由注释可知,只要有改变,modCount就会加上1;
那我代码里的remove()方法又为什么会引起异常呢?
在ArrayList中的内部类Itr中的next()方法中可以看到:

一开始会调用checkForComodification();方法进行检查,初始时,cursor为0,lastRet为-1,在调用一次之后,cursor的值为1,lastRet的值为0,modCount为0,expectedModCount也为0。
再来看代码中的remove()方法做了什么:

在这里调用了ArrayList.this.remove(lastRet);
- 对于iterator,其expectedModCount为0,cursor的值为1,lastRet的值为0;
- 对于list,其modCount为1,size为0;
那么在下一次调用时,执行checkForComodification()方法,就会遇到ConcurrentModificationException异常了,问题在于:调用list.remove()方法导致modCount和expectedModCount的值不一致。

解决(18年)
我解决的方法是改成索引遍历,但是需要在删除之后保证索引的正常:

摘自: