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

x33g5p2x  于2021-08-12 转载在 Java  
字(7.4k)|赞(0)|评价(0)|浏览(370)

前言

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

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

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

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

哦对了,项目JobBridge主要是实现一个求职平台,作为企业与求职者的桥梁。我们的代码开源在:JobBridge

问题

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

这里写图片描述

这里写图片描述

原因

简单地说下原因,在我那个项目的代码中,遍历的方式是用Itr去遍历的,这个Itr是ArrayList实现的一个遍历接口、内部类。

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

ArrayList的remove方法修改的变量是继承自AbstractList的变量modeCount;而Itr的remove方法修改的是自身的变量expectedModCount。

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

另,貌似直接用Itr的remove方法也可以解决问题,不需要像我最后的处理方式那样复杂。并且,ArrayList 是一个查询为主的数据结构,本身就不太适合修改频繁以及并发修改的场景。

在这里插入图片描述

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

分析

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

import java.util.ArrayList;

class Test{ 
    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 Test.java

C:\Users\hzy\Desktop>java Test
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重新赋值,所以就抛出异常了。

– 于2021.4.11修改(解决方案在文章末尾…


下面是以前的文章的内容了… 写的烂七八糟的,舍不得删了hh

最后在网上看了一下,才发现是循环的时候,进行了删除的操作,所以才会报错,原因在于: 迭代器的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的值不一致
这里写图片描述



解决

我解决的方法是改成索引遍历,但是需要在删除之后保证索引的正常:
这里写图片描述
参考:Java ConcurrentModificationException 异常分析与解决方案

相关文章

微信公众号

最新文章

更多