前言

二十多天的实训结束了,虽然环境emmmm有点坑,好多人都感冒了,我也没能逃过一劫. 不过总体来说还行, 第一次尝试跟学校里不一样的,7个人一起做项目. 不过也因此对于github的使用不再局限于之前的将其作为云服务备份来使用了,更多的还是大家上传代码,合并冲突之类的,还有也学会了git stash的一些个基础用法,嘻嘻.
这个月还没写点东西记录一下. 这里就记录一下之前遇到过的一个,算是比较突然,意想不到的错吧.
以下有的是网上查到的资料,再加上了一点点自己的理解,感觉还是有些地方不太懂,如果有什么错误还请批评指正.



问题:

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

这里写图片描述

这里写图片描述

原因:

最后在网上看了一下,才发现是循环的时候,进行了删除的操作,所以才会报错,原因在于: 迭代器的modCount和expectedModCount的值不一致;
我代码中的这个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的值不一致

值得一提的是,在递归调用list添加元素时也会产生此种异常。


这里写图片描述



解决

我解决的方法是改成索引遍历,但是需要在删除之后保证索引的正常: 
这里写图片描述

还可以用倒序,见下面的附图

 

 

 


参考:Java ConcurrentModificationException 异常分析与解决方案

 
posted on 2020-11-25 09:47  yuluoxingkong  阅读(417)  评论(0编辑  收藏  举报