Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the iterator is failsafe in concurrent hash map

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

like image 525
Girish Avatar asked Jan 07 '15 18:01

Girish


1 Answers

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:

  • If node it currently holds have been removed, jump to next bin (by incrementing index)
  • Optimistic 'locking' (i.e. just try again) for cases when hash table can be in inconsistent state
  • Special type of node (ForwardingNode) to detect rehash

See ConcurrentHashMap.Traverser.advance() method.

like image 71
Sergey Alaev Avatar answered Oct 05 '22 06:10

Sergey Alaev