java.util.ConcurrentModificationException 异常原因和解决方法

java.util.ConcurrentModificationException 异常原因和解决方法前言二十多天的实训结束了 虽然环境 emmmm 有点坑 好多人都感冒了 我也没能逃过一劫 不过总体来说还行 第一次尝试跟学校里不一样的 7 个人一起做项目 不过也因此对于 github 的使用不再局限于之前的将其作为云服务备份来使用了 更多的还是大家上传代码 合并冲突之类的 还有也学会了 gitstash 的一些个基础用法 嘻嘻 这个月还没写点东西记录一下 这里就记录一下之前遇到过的一个 算

前言

二十多天的实训结束了,虽然环境emmmm有点坑,好多人都感冒了,我也没能逃过一劫。

不过总体来说还行,第一次尝试跟学校里不一样的,7个人一起做项目。 不过也因此对于github的使用不再局限于之前的将其作为云服务备份来使用了,更多的还是大家上传代码,合并冲突之类的,还有也学会了git stash的一些个基础用法,嘻嘻。

这个月还没写点东西记录一下。 这里就记录一下之前遇到过的一个,算是比较突然,意想不到的错吧。

以下有的是网上查到的资料,再加上了一点点自己的理解,感觉还是有些地方不太懂,如果有什么错误还请批评指正。

哦对了,项目JobBridge主要是实现一个求职平台,作为企业与求职者的桥梁。

我们的代码开源在:JobBridge

问题

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

这里写图片描述

这里写图片描述

原因

简单地说下原因,在我那个项目的代码中,遍历的方式是增强 for 循环,在底层使用的也是迭代器。

也就是说,是用Itr去遍历的,这个Itr是ArrayList实现的一个遍历接口、内部类。

但是我在删除的时候是通过ArrayList的remove方法去操作的,不是Itr内部的那个删除方法去操作的。

那么问题就来了:

ArrayList的remove方法修改的变量是继承自AbstractList的变量modCount;而Itr的remove方法修改的是自身的变量expectedModCount。这两个变量的作用都是记录修改次数的。

所以,在用ArrayList的remove方法进行删除操作以后,Itr里面的expectedModCount会与ArrayList的modCount进行比较,二者不相等,所以会抛错。

在这里插入图片描述

(很久没画过UML图了,有画错的还请指出,捂脸…

源码分析

这里我写了一个方便问题复现的代码:

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重新赋值,所以就抛出异常了。

解决方法

  1. 改成Iterator的迭代方式,用内部类Itr的remove方法来删除,保证一致性:
    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(Iterator<Integer> it=arr.iterator(); it.hasNext();){ 
          Integer i = it.next(); if(i == 5){ 
          it.remove(); } else{ 
          System.out.println(i); } } } } 
  2. 每次删除的时候都让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); } } } } 
  3. 倒序删除,先遍历一遍记录要删除的下标,然后从末尾开始删除

另,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这个内部类的实现:
由注释可以看到:

  1. cursor是下一个返回的元素的下标;
  2. lastRet 是最后一个返回的元素的索引下标;
  3. expectedModCount:是对ArrayList修改次数的预期的数值,被初始化为modCount; 注意,这里expectedModCount是内部类 Itr 中的变量,而modCountArrayList继承自AbstractList的一个成员变量
  4. 在这个内部类的末尾我看到了, 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.javactrl 点一下 modCount找一下,发现modCountArrayList继承自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);














  1. 对于iterator,其expectedModCount为0,cursor的值为1,lastRet的值为0;
  2. 对于list,其modCount为1,size为0;

那么在下一次调用时, 执行checkForComodification()方法,就会遇到ConcurrentModificationException异常了,问题在于:调用list.remove()方法导致modCountexpectedModCount的值不一致
这里写图片描述

解决(18年)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/211268.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 下午10:49
下一篇 2026年3月18日 下午10:50


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号