我正在迭代一个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/