【Java源码分析】ConcurrentModificationException并发修改异常分析与解决方案(快速失败与安全失败)

来源:互联网 发布:网络教育网络统考 编辑:程序博客网 时间:2024/05/18 00:48

【Java源码分析】ConcurrentModificationException并发修改异常分析与解决方案(快速失败与安全失败)

问题描述

当执行如下程序时,会抛出异常 java.util.ConcurrentModificationException

public static void main(String ... args){    Collection<String> coll = new ArrayList<>();    coll.add("llll");    coll.add("oooo");    coll.add("hhhh");    coll.add("cccc");    Iterator<String> iter = coll.iterator();    while(iter.hasNext()){        String val = iter.next();        if ("hhhh".equals(val))            System.out.println(val);        coll.remove(val);   // java.util.ConcurrentModificationException    }}

异常信息如下:

Exception in thread "main" java.util.ConcurrentModificationException    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)    at java.util.ArrayList$Itr.next(ArrayList.java:851)    at javaenhance.part04_thread.java5thread.CollectionConcurrentModifyExceptionTest.main(CollectionConcurrentModifyExceptionTest.java:28)    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)    at java.lang.reflect.Method.invoke(Method.java:498)    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

源码分析

查看 ArrayList$Itr.next()方法,源代码如下:

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];}

它会首先执行 checkForComodification() 方法,其源码如下:

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

这里,if的判断条件成立时,就会抛出异常 ConcurrentModificationException。
这个条件什么时候成立呢?
我们来分析一下其中的两个变量 modCount 和 expectedModCount。

modCount是AbstractList中的成员变量,定义如下:

protected transient int modCount = 0;
简单地说,modCount表示一个集合中元素个数变化的次数,或者说是集合对象的版本号。

expectedModCount 是Array$Itr中的成员变量,定义如下:

int expectedModCount = modCount;

当集合调用iterator()方法时,会创建一个Iterator对象,此时,会初始化 expectedModCount 为 modCount;

expectedModCount的值不会发生变化,而当对集合对象执行remove和add等操作时,modCount的值会发生变化,所以将会产生两者不相等的情况,也就是抛出异常的条件成立的情况,所以会抛出异常 ConcurrentModificationException。

解决方案

解决方案就是,使用线程安全的集合类,Java5提供的并发库中的集合, CopyOnWriteArrayList。
代码如下

@Testpublic void concurrentCollectionTest(){    Collection<String> coll = new CopyOnWriteArrayList<>();    coll.add("llll");    coll.add("oooo");    coll.add("hhhh");    coll.add("cccc");    Iterator<String> iter = coll.iterator();    while(iter.hasNext()){        String val = iter.next();        if ("hhhh".equals(val))            coll.remove(val);   // java.util.ConcurrentModificationException        System.out.println(val);    }}

快速失败与安全失败的区别

快速失败(fail—fast)

在用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了修改(增加、删除、修改),则会抛出Concurrent Modification Exception。

原理:
迭代器在遍历时直接访问集合中的内容,并且在遍历过程中使用一个modCount 变量。集合在被遍历期间如果内容发生变化,就会改变modCount的值。每当迭代器使用hashNext()/next()遍历下一个元素之前,都会检测modCount变量是否为expectedmodCount值,是的话就返回遍历;否则抛出异常,终止遍历。

注意:
这里异常的抛出条件是检测到 modCount!=expectedmodCount 这个条件。如果集合发生变化时修改modCount值刚好又设置为了expectedmodCount值,则异常不会抛出。因此,不能依赖于这个异常是否抛出而进行并发操作的编程,这个异常只建议用于检测并发修改的bug。

场景:
java.util包下的集合类都是快速失败的,不能在多线程下发生并发修改(迭代过程中被修改)。

安全失败(fail—safe)

采用安全失败机制的集合容器,在遍历时不是直接在集合内容上访问的,而是先复制原有集合内容,在拷贝的集合上进行遍历。

原理:
由于迭代时是对原集合的拷贝进行遍历,所以在遍历过程中对原集合所作的修改并不能被迭代器检测到,所以不会触发Concurrent Modification Exception。

缺点:
基于拷贝内容的优点是避免了Concurrent Modification Exception,但同样地,迭代器并不能访问到修改后的内容,即:迭代器遍历的是开始遍历那一刻拿到的集合拷贝,在遍历期间原集合发生的修改迭代器是不知道的。

场景:
java.util.concurrent包下的容器都是安全失败,可以在多线程下并发使用,并发修改。


参考 :
ArrayList和AbstractList的源码
快速失败(fail-fast)和安全失败(fail-safe)的区别是什么

阅读全文
1 0