在使用foreach循环遍历集合的过程中,如果集合被修改了,会抛出ConcurrentModificationException异常。
以这段代码为例子:
public class SynProblem {
List<Widget> widgetList = Collections.synchronizedList(new ArrayList<>());
{
widgetList.add(new Widget(1));
widgetList.add(new Widget(2));
widgetList.add(new Widget(3));
}
public void test() {
for (Widget w : widgetList) {
doSomethings(w);
}
}
private void doSomethings(Widget w) {
System.out.println(w);
}
public static void main(String[] args) {
SynProblem s = new SynProblem();
s.test();
}
}
使用javap反编译一下,可以看到在test方法中,for循环调用了iterator接口的方法

问题来了,foreach循环底层也是调用了iterator的方法,为什么在foreach循环add/remove集合元素,可能会抛出 ConcurrentModificationException 异常,但是使用iterator来remove 集合元素却不会呢?
下面以ArrayList为例:
调用ArrayList.iterator()返回的是ListItr,这是ArrayList的内部类,实现了Iterator接口
private class Itr implements Iterator<E> {
int cursor; //下一个返回元素索引
int lastRet = -1; //最后一个返回元素索引,如果被remove该索引会被重置为-1
int expectedModCount = modCount;//期待修改次数(可被视为 Itr内部记录的集合结构变化次数)
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();//1.
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);//调用集合的删除操作,modCount+1
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;//重新给expectedModCount赋值
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)//如果期待修改次数与实际修改次数不同,则抛出异常
throw new ConcurrentModificationException();
}
}
而ArrayList的add方法,也会进行modCount ++
可以看到的是在foreach循环会调用next()方法,next方法会调用checkForComodification()来检查modCount 是否等于expectedModCount。要注意的是如果在for循环中直接使用add或者remove操作,是不会有下面这一步的。也就是说此时modCount != expectedModCount。抛出异常。这是java的 fail-fast 策略,用来防止多线程并发修改集合时,保证数据的一致性。
![]()
本文探讨了在使用Java的foreach循环遍历集合时,如果集合被修改,为何会抛出`ConcurrentModificationException`异常。通过反编译代码,揭示了foreach循环底层调用Iterator接口,并介绍了ArrayList的`ListItr`内部类以及`fail-fast`策略。当在循环中直接使用add或remove,导致`modCount`不等于`expectedModCount`,因此引发异常,以保证数据一致性。
6189

被折叠的 条评论
为什么被折叠?



