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.
如果您查看 values
、entrySet
和 keySet
方法:
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/