5

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 library.

Bhaskar
  • 7,443
  • 5
  • 39
  • 51
  • each write (put) is proceeded by a lock acquisition (plus volatile write)that ensures the 'visibility'. Each read (get) does a volatile read which ensures the visibility for the reader. – bestsss Oct 27 '11 at 16:20

1 Answers1

6

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.

John Vint
  • 39,695
  • 7
  • 78
  • 108
  • Yes, I see now the `class HashEntry` has a `volatile` Value. Earlier , I was just checking the `HashEntry[] table` reference. – Bhaskar Oct 27 '11 at 14:14
  • It's a good question though, seemed odd to me the first time I learned that CHM was a partially non-blocking algorithm – John Vint Oct 27 '11 at 14:53
  • CHM is (always was) non-blocking on read. Put is realized via lock elision which is ok more or less but it doesn't scale too well. The CAS does exists to acquire the lock, though. http://sourceforge.net/projects/high-scale-lib/ here a version that doesn't block on either write or read. – bestsss Oct 27 '11 at 16:23
  • Yea, the CAS is done on tryAcquire. I was more of implying there is no explicit use of CAS on the CHM itself similar to the CHMv8 release candidate for Java 8 – John Vint Oct 27 '11 at 17:15