Java ConcurrentModificationException问题解决

为什么会抛出java.util.ConcurrentModificationException异常

(如有错误,欢迎指正)

在这里插入图片描述
先看一下这一段代码,看起来没有什么问题 但是运行会出现以下异常
在这里插入图片描述
首先java的foreach循环其实就是根据list对象创建一个Iterator迭代对象,用这个迭代对象来遍历list,相当于list对象中元素的遍历托管给了Iterator,你如果要对list进行增删操作,都必须经过Iterator,否则Iterator遍历时会乱,所以直接对list进行删除时,Iterator会抛出ConcurrentModificationException异常
其实,每次foreach迭代的时候都有两部操作:

  1. iterator.hasNext() //判断下个元素是否存在
  2. info= iterator.next() //将下个元素赋值给info
一些相关的方法的代码如下:
首先看ArrayList的iterator()方法:
    public Iterator<E> iterator() {
        return new Itr();
    }
从这段代码可以看出返回的是一个指向Itr类型对象的引用,我们接着看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();
        }
    }
几个成员变量解释如下:
  1. cursor:表示下一个要访问的元素的索引
  2. lastRet:表示上一个访问的元素的索引
  3. expectedModCount:Iterator:期望这个list被修改的次数,初始值为modCount
  4. modCount:表示对list的修改次数,当调用List的add或者remove方法的时候,这个modCount加一或减一
当调用list.iterator()之后,通过hashNext()方法判断是否还有元素未被访问,hasNext()方法实现如下:
public boolean hasNext() {
            return cursor != size;
        }
然后通过进到next()方法,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()方法,然后将下一个元素的索引赋值给i并且检验i的大小抛出对应异常,若i的范围值正确,sursor+1;并且将此时的索引值i赋值给lastRet ,初始时cursor为0,lastRet为-1,调用一次之后,此时的cursor的值为1,lastRet的值为0。

再看一下ArrayList中的remove()方法
 public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }


    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

通过remove方法删除元素最终是调用的fastRemove()方法,在fastRemove()方法中,首先对modCount进行加1操作(修改了一次),然后接下来就是删除元素的操作,最后将size进行减1操作,并将引用置为null以方便垃圾收集器进行回收工作。

那么此时各个变量的值:对于iterator,其expectedModCount为0,cursor的值为1,lastRet的值为0。对于list,其modCount为1,size为0。

执行完删除操作后,继续while循环,调用hasNext方法()判断,由于此时cursor为1,而size为0,那么返回true,所以继续执行while循环,然后继续调用iterator的next()方法:注意,此时要注意next()方法中的第一句:checkForComodification()。

在checkForComodification方法中进行的操作是:

final void checkForComodification() {
    if (modCount != expectedModCount)
    throw new ConcurrentModificationException();
}
这个时候会发现抛出异常的原因在于modCount != expectedModCount

那么为什么modCount 不等于expectedModCount了呢?
iterator创建的时候,modCount被赋值给了expectedModCount,但是调用add和remove方法的时候不会同时自动增减expectedModCount。
调用list.remove()方法导致modCount和expectedModCount的值不一致。

解决方案如下

查看源码知道Itr中也定义了一个remove()方法

public void remove() {
    if (lastRet == -1)
    throw new IllegalStateException();
       checkForComodification();
    try {
    AbstractList.this.remove(lastRet);
    if (lastRet < cursor)
        cursor--;
    lastRet = -1;
    expectedModCount = modCount;
    } catch (IndexOutOfBoundsException e) {
    throw new ConcurrentModificationException();
    }
}

实质上也是调用list.remove()方法 但是多了一句expectedModCount = modCount;
所以 在迭代器下删除元素 可以调用Itr.中的remove方法就不会报错

单线程下解决方案

将之前的代码如下修改即可
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值