简体   繁体   English

ConcurrentHashMap中的失败安全迭代器

[英]fail safe iterator in ConcurrentHashMap

Iterators in both CopyOnWriteArrayList and ConcurrentHashMap are fail-safe and do not throw CME. CopyOnWriteArrayListConcurrentHashMap中的迭代器都是故障安全的,不会抛出CME。

IN CopyOnWriteArrayList<E> iterator is built on a snapshot of original underlying array. IN CopyOnWriteArrayList<E>迭代器建立在原始基础数组的快照上。 So iterator here is fail-safe and also thread-safe. 因此,这里的迭代器是故障安全的 ,也是线程安全的。

Javadcos for CopyOnWriteArrayList<E> clearly states term snapshot . 用于CopyOnWriteArrayList<E> Javadcos清楚地说明了术语快照

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. 此数组在迭代器的生命周期内永不更改,因此不可能发生干扰,并且保证迭代器不会引发ConcurrentModificationException。

Does in case of ConcurrentHashMap iterator also built on snapshot of original underlying map? ConcurrentHashMap迭代器的情况下,是否也建立在原始基础地图的快照上?

Thanks... 谢谢...

Not necessarily - cf the javadoc (emphasis mine) : 不一定-cf javadoc(强调我的)

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 . 类似地,迭代器和枚举返回的元素反映了在创建迭代器/枚举时或之后的某个时刻哈希表的状态。

If you look at the values , entrySet and keySet methods: 如果查看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. 视图的迭代器保证遍历迭代器构造时存在的元素,并且可以(但不保证)反映构造之后的任何修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM