Java并发修改异常: Is it possible to add elements to a hashtable while iterating through it?

标签 java exception concurrency

我正在迭代一个Hashtable,并且在某一时刻,我向Hashtable添加了一些东西,这显然给了我一个ConcurrentModificationException。我明白为什么会收到错误,但是有没有办法解决这个问题,以便我仍然可以迭代 Hashtable 并同时添加值?

最佳答案

来自文档

The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Hashtable's keys and elements methods are not fail-fast.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

如果您需要这种行为,您可以安全地复制键集并迭代该副本。如果哈希表很大并且复制键集可能很昂贵,则另一种选择是在迭代期间添加到单独的集合,并在迭代后添加单独集合的元素。

关于Java并发修改异常: Is it possible to add elements to a hashtable while iterating through it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5334179/

相关文章:

java - 在此类的对象上调用 start() 安全吗? Java 并发实践中的一个例子

java - 检查 HashMap 中是否已存在某个值,如果存在则允许用户输入有效值

java - 我在使用抛硬币程序时遇到一些问题

java - Fragment 和 ListFragment 不兼容

swing 未捕获的异常处理程序

java - 如何使用读写锁

java - 来自 javax.validation.constraints 的注释与自定义 ConstraintValidator 相结合

c++ - 从 Lua 调用函数时如何处理 C++ 异常?

ruby - 结合 `raise` 和 `throw`

java - 同步多个异步请求