java - ConcurrentHashMap 中的故障安全迭代器

标签 java collections

CopyOnWriteArrayList 中的迭代器和ConcurrentHashMap具有故障安全功能,不会引发 CME。

IN CopyOnWriteArrayList<E>迭代器是建立在快照之上的 原始底层数组。所以这里的迭代器是故障安全并且也是线程安全的。

Javadcos CopyOnWriteArrayList<E>明确指出术语快照

The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.

ConcurrentHashMap 的情况下是否如此迭代器也是建立在原始底层 map 的快照之上吗?

谢谢...

最佳答案

不一定 - 参见 the javadoc (emphasis mine) :

Similarly, Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration.

如果您查看 valuesentrySetkeySet 方法:

The view's iterator [...] guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

关于java - ConcurrentHashMap 中的故障安全迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12800098/

相关文章:

php - 如何更改 mongodb 中的集合结构?

java - 是否建议用初始容量初始化arraylist

java - 带有 slf4j 和 log4j 的 hibernate 3.4

java.util.Collections$UnmodifiableRandomAccessList 到 Collections.singletonList

java - 流与集合

java - 更改绘画面板中的绘画图像

java - 迭代器和 For Each 循环的区别

java - spring data jpa实体从未被id找到

Java - 打印分割字符串的几个不同部分

java - 无法在第 42 行中产生静态引用错误