java问题排查-ConcurrentModificationException

场景:需要在List迭代过程中删除满足条件的元素时,代码报出ConcurrentModificationException异常。代码如下:

ArrayList list = new ArrayList();
list.add(new Person("a"));
list.add(new Person("b"));
list.add(new Person("c"));
list.add(new Person("d"));
for (Person p:list){
    if ("c".equals(p.getName())) {
        list.remove(p);
    }
    System.out.println(p.getName());
}
//错误信息
a
b
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)

        查看错误信息,发现是在List迭代过程中报错的,也就是在for (Person p:list)这个语句中报错。我们知道Java中foreach语句是一种语法糖,通过将class文件反编译,我们可以看到如下结果:

java问题排查-ConcurrentModificationException_第1张图片

       foreach语句实际上是通过调用list的Iterator进行遍历,本例中使用的是ArrayList,进入到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];
}
final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

        迭代过程中,当调用Itr的next()方法时,首先会调用一个checkForComodification方法,这是一个fanal方法(子类不可重写),这个方法只做了一个modCount与expectedModCount的比较动作。那么这个modCount与expectedModCount又代表什么呢。modCount是ArrayList中的一个字段,字段上有一段说明:

The number of times this list has been structurally modified.Structural modifications are those that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.

This field is used by the iterator and list iterator implementation returned by the {@code iterator} and {@code listIterator} methods. If the value of this field changes unexpectedly, the iterator (or list iterator) will throw a {@code ConcurrentModificationException} in response to the {@code next}, {@code remove}, {@code previous}, {@code set} or {@code add} operations. This provides fail-fast behavior, rather than non-deterministic behavior in the face of concurrent modification during iteration.

       翻译一下就是:这个modCount这个list在结构上被修改的次数 。所谓结构修改是指改变列表的大小,或者以一种正在进行的迭代可能产生错误结果的方式扰乱列表。如果该字段的值发生意外变化,迭代器(或列表迭代器)将抛出一个ConcurrentModificationException来响应{@code next}、{@code remove}、{@code previous}、{@code set}或{@code add}操作。这提供了故障快速行为,而不是在迭代过程中面对并发修改时的不确定性行为。

       也就是list的add、remove这些增加list大小的操作都会被记录在modCount上,在我们代码中,初始一个list后,进行add操作,add方法中,对modCount进行++操作,在迭代前modCount=4。

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}
private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
    
    modCount++;
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

       说完modCount,再来看看expectedModCount这个字段。 这个字段是属于迭代器Itr的一个属性。在调用list的iterator()的方法时,该方法会实例化一个Itr返回,expectedModCount的初始值等于实例化时list的modCount

java问题排查-ConcurrentModificationException_第2张图片

       看到这里,想必大概就明白了。在进入迭代时,expectedModCount表示了当前时刻list的一个状态,在调用next方法时,会首先判断expectedModCount是否等于modCount,也就是判断list是否有过结构修改。在迭代过程中,若list被修改过(add,remove操作),那么迭代就会抛出ConcurrentModificationException异常。

 

        明白了异常抛出的原因,在这里有两个疑问需要进一步探究,一是如何在遍历list过程中对list进行修改呢?另一个是List为什么要这样设计,这样设计的原因是什么?

先看第一个问题,既然在迭代时不能通过list的remove方法删除元素,那么首先想到的是通过li下标index遍历list,并删除元素,代码如下:

ArrayList list = new ArrayList();
list.add(new Person("a"));
list.add(new Person("b"));
list.add(new Person("c"));
list.add(new Person("d"));
for (int i=0;i

这种方式删除元素直接通过list内部数组删除,效率更高。

除了这种方式,在ArrayList迭代器中,提供了一个remove方法。该remove方法代码如下:

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();
    }
}

       代码中lastRet是迭代器上一个返回值的下标,该方法删除元素实际上也是调用了list的remove方法,但在删除后,将list的modCount重新赋值给expectedModCount,因此下一次迭代执行checkForComodification()就不会报ConcurrentModificationException异常。使用迭代器remove方法代码如下:

ArrayList list = new ArrayList();
list.add(new Person("a"));
list.add(new Person("b"));
list.add(new Person("c"));
list.add(new Person("d"));
Iterator iterator = list.iterator();
while (iterator.hasNext()){
    Person pp = iterator.next();
        if ("b".equals(pp.getName())) {
            //删除上一个next方法返回的值,因此调用remove方法前,需调用next方法
            iterator.remove();
        }
    }

        解决了第一个问题,再看第二个问题,另一个是List为什么要这样设计,这样设计的原因是什么?在前面的介绍modCount字段时,有一句话:这提供了一种fail-fast机制,而不是在迭代过程中面对并发修改时的不确定性行为。也就是说,这种fail-fast机制在迭代过程中检测到list发生结构性变化时,会快速抛出CME异常,这样做的好处是提前考虑异常情况,避免出现不确定的行为。

       这里举一个简单的例子,一个线程在开始对ArrayList进行遍历时,list中有1、2、3三个值,这时期望的结果是遍历一个值打印出结果最终打印出1、2、3三个值。但在遍历过程中,另一个线程删除了list中的第三个值,这时若第一个线程继续遍历,最终打印出来的只有1、2两个值,这显然与期望的结果不符。而fail-fast机制在检测到list的第三个值被删除之后,第一个线程在遍历时就会抛出CME异常,通过CME异常来避免不确定的结果出现。

你可能感兴趣的:(java问题排查,java,fail-fast,迭代器)