简体   繁体   中英

Traversal in ConcurrentHashMap

  1. Why is value in the Entry class of ConcurrentHashMap volatile.

  2. During traversal, there is a check in ConcurrentHashMap that when the value in the Entry class in null, it locks the whole segment and tries to read the value again. In which case can the value alone be null? The whole entry should go null and not only the value.

  3. And how locking the whole segment ensures correct traversal in case the value comes null.

  1. The value is volatile primarily so that the ConcurrentHashMap does not need to block on reads. When put 'ing the CHM will lock the segment to guarantee one put per segment but other Thread's are still allowed to read from that segment, and since the value is volatile the CHM still maintains a happens-before ordering.

  2. The JMM allows for a volatile store in a constructor to be delayed or reordered after the object has been published. So it could be possible that, even though the Entry is published, the volatile field has yet to be made visible. This was put in to be 'extra-safe' but in practice wouldn't happen (in Java 6 at least)

  3. When the put is made, it is done so under the Segment's lock. When acquiring that same lock you guarantee the subsequent write will be now visible to any reads after said write (this is another guarantee for Lock and synchronized where a write occurring under a lock will be visible to any future reads under the same lock, this does not hold true for a lock write and a volatile read however).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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