在Java中,如何在单线程程序中抛出ConcurrentModificationException? [英] In Java how can this throw a ConcurrentModificationException in a single threaded program?

查看:144
本文介绍了在Java中,如何在单线程程序中抛出ConcurrentModificationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读这篇 Freuqent Java并发问题的问题,并被一个回答困惑,说: java.util.ConcurrentModificationException

I was reading this "Freuqent Java concurrency problems" question and got confused by an answer talking about java.util.ConcurrentModificationException.

我的理解答案是,这可能发生在单线程程序。
如何或什么条件导致以下代码抛出异常?

My understanding of the answer is that this can occur in a single-threaded program. How or what conditions cause the following code to throw the exception?

List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c"));
for (String string : list) { list.remove(string); }


推荐答案

此片段将始终< > throw a ConcurrentModificationException

规则如下:您不能修改list),同时使用Iterator迭代它(当你使用for-each循环时会发生这种情况)。

The rule is the following: You may not modify (add or remove elements from the list) while iterating over it using an Iterator (which happens when you use a for-each loop).

注意,你可以通过迭代器修改列表(因为它知道修改,并且可以考虑修改)使用 Iterator.remove ListIterator.add

Note however that you are allowed to modify the list through the iterator (because then it is aware of the modification, and can take it into account) using the Iterator.remove or ListIterator.add.

从文件:


通过这个类的迭代器和listIterator方法是fail-fast:如果列表在迭代器创建之后的任何时候被结构性地修改,除了通过迭代器自己的remove或add方法之外,迭代器将抛出一个ConcurrentModificationException。

这里的并发这里指的是您在遍历。

The word concurrent here refers to that you're modifying the list during traversal.

这篇关于在Java中,如何在单线程程序中抛出ConcurrentModificationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆