简体   繁体   中英

ConcurrentHashMap non-blocking reads and memory visibility issue

ConcurrentHashMap in Java offers reads to proceed concurrently with updates. The trade-off in this is that the results of the read is limited to reflect only the last completed update when the reading began, so it is not specified to reflect the latest state of elements.

However AFAIK Java Memory Model , without some form of synchronization between the read and write threads, the updates of the write thread may not become visible to the read thread , even after arbitrary period of time.

Given the read threads do not block with write threads , what forms the basis of the guarantee of visibility of the last completed update to be available to the read thread ?

I could only think of something on the lines of Compare-and-swap algorithm at play but I could not verify it in the source code of that labrary.

The read of the values are actually volatile loads. Though it is non-blocking you will ensure the happens-before relationship since the store too is volatile.

Java 5,6,7's version of the CHM does not use CAS to swap the references. But there is a newer lightweight version in the works that would use in some of its writes.

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