ConcurrentModificationException异常原因以及解决方法

1.情景描述

代码一:

public class Test {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		
		list.add("a");
		list.add("b");
		list.add("c");
		list.add("d");
		
		for (String string : list) {
			list.remove(string);
		}
	}
}

运行结果:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at pattern.Test.main
(Test.java:22)

代码二:

public class Test2 {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();

		list.iterator();

		list.add("a");
		list.add("b");
		list.add("c");
		list.add("d");

		for (int i = 0; i < list.size(); i++) {
			String string = list.get(i);
			list.remove(string);
			System.out.println("移除了元素:" + string);
		}
	}
}

运行结果:

移除了元素:a
移除了元素:c

2.提出问题

为什么代码一会出现ConcurrentModificationException代码二却可以正确执行?

3.问题解答

相信有点基础的同学都知道增强for循序遍历实际上是借助Iterator(迭代器)来实现的遍历。

这一点通过debug的调用堆栈我们也可以得到。

增强for循环调用堆栈

那么问题又来了,为什么使用Iterator(迭代器)就会出现ConcurrentModificationException

通过调用堆栈我们可以看出程序先调用了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];
        }

可以看出next()方法首先会调用checkForComodification()方法。(与调用堆栈相匹配)

再看看checkForComodification()方法。

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

checkForComodification()方法会比较modCountexpectedModCount的值,当modCountexpectedModCount的值不相等时就会抛出ConcurrentModificationException异常了。

看到这里我们终于知道了ConcurrentModificationException异常是从哪里抛出来的了。 ------>>   答:当modCountexpectedModCount的值不相等时。

那么什么情况下会导致modCountexpectedModCount的值不相等呢?

想要了解这个问题首先要知道modCountexpectedModCount都是什么东西。

点击modCount我们得到modCountAbstractList类的一个属性

protected transient int modCount = 0;// AbstractList的一个属性

下来再来看看expectedModCount这个属性。

很明显expectedModCountItr的一个属性。

    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;

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

当我们用增强for循环遍历集合时,遍历第一个元素时,首先会实例化Itr类,实例化Itr类时会初始化Itr类的expectedModCount属性。

int expectedModCount = modCount;

显然这时候modCount==expectedModCount

然后我们移除一个元素,调用list.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;
    }

我们会走到else代码块。

else代码块里会在集合中搜索我们想要移除的元素,找到后调用fastRemove(index)方法。

   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
    }

fastRemove(index)方法一上来会对modCount+1,之后做移除的操作。移除完后我们接着遍历,调用Itr.next()方法,这时候我们的modCount已经+1expectedModCount的值还是原来的值,显然modCount!=expectedModCount

这时候自然而然就出现了ConcurrentModificationException异常。

4.如何解决

4.1单线程环境下

细心的朋友可能已经发现了,我们的Itr类也有一个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();
            }
        }

如果使用Itr.remove()方法它再最后总会调用expectedModCount = modCount;这样就不会出现异常了,因此我们改造代码一

public class Test {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		
		
		
		list.add("a");
		list.add("b");
		list.add("c");
		list.add("d");
		
		Iterator<String> iterator = list.iterator();
		
		while (iterator.hasNext()) {
			String next = iterator.next();
			iterator.remove();
			System.out.println("移除了元素:" + next);
		}
		
	}
}

运行结果:

移除了元素:a
移除了元素:b
移除了元素:c
移除了元素:d

4.2多线程环境下

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值