前言

在操作List集合的时候,习惯用for each循环操作。这次项目中根据业务逻辑需要删除符合条件的元素,元素删除后,继续next操作,抛出了ConcurrentModificationException异常。下面,重现异常,看看异常是怎么发生的,怎么避免。

测试代码

public class ConcurrentModificationExceptionList {  
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        for (Integer integer : list1) {
            if (integer == 1) {
                list1.remove(integer);
            }
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

异常的发生

ConcurrentModificationException异常是在这里抛出的。当modCount != expectedModCount为true的时候抛出。

Java ArrayList异常-ConcurrentModificationException_List

Java ArrayList异常-ConcurrentModificationException_并发修改异常_02

原因

上述异常为什么会发生,来看一下源码中的删除动作。

Java ArrayList异常-ConcurrentModificationException_解决方案_03

Java ArrayList异常-ConcurrentModificationException_List_04

在执行删除动作前modCount自加1。在下个元素做checkForComodification的时候异常就抛出了。

Java ArrayList异常-ConcurrentModificationException_ArrayList_05

异常的解决

Java ArrayList异常-ConcurrentModificationException_List_06

查看源码,modCount是在ArrayList的父类AbstractList中定义的,modCount记录list被修改的次数。在iterator和实现iterator的list中,进行next(),remove()、previous、set、add操作时,modCount的值被意外改变,将抛出异常ConcurrentModificationException。关于异常的解决,网上也有很多的方法,参考文末。

既然异常是在iterator和实现iterator的list中发生的,那不使用for each操作,采用for in操作就能避免异常的发生。

代码验证一下

for (int i = 0; i < list1.size(); i++) { if (list1.get(i)==1){ list1.remove(i); i--;//指向删除前的上一个元素 }
        }
  • 1.
  • 2.

Java ArrayList异常-ConcurrentModificationException_并发修改异常_07

看一下源码:

Java ArrayList异常-ConcurrentModificationException_并发修改异常_08

源码中是没有做checkForComodification检查的,也不会发生异常。

参考

Java ConcurrentModificationException异常原因和解决方法
集合迭代时对集合进行修改抛ConcurrentModificationException原因的深究以及解决方案
Java ConcurrentModificationException 异常分析与解决方案