As I know that iterator in the CopyOnWriteArrayList
is thread-safe due to snapshot reference to the copy of arrayList
at the time of iterator is created, and in this all mutative operations (add, set, and so on)
are implemented by making a fresh copy of the underlying array so they do not affect the copy referred by snapshot reference and same for CopyOnWriteArraySet
,
But struggling in case of ConcurrentHashMap
, so please share your views how the iterator is fail-safe in case of ConcurrentHaspMap
Regarding Java8 ConcurrentHashMap implementation.
Despite javadoc, ConcurrentHashMap Iterator does NOT return a snapshot, it operates on live concurrent hash table handling all concurrency cases optimistically, in the same way all lock-free data structures do.
Basically, it contains reference to current hashtable, bin index in that hashtable and last returned Node. Here are some tricks it uses to operate on concurrent hash table w/o locking:
See ConcurrentHashMap.Traverser.advance() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With