Search code examples
javaconcurrencyconcurrenthashmap

Is it safe to use ConcurrentHashMap for things like balance storage


Good day, I was looking at the source code of ConcurrentHashMap(CHM) in Java 8 and found that method get is lock free. It just makes a volatile read from the array of nodes in order to read the latest value from main memory. Let's say that I have two threads which read and write from map using the same key. With lock free approach reader thread won't wait while writer will update the value. In this case I can't use CHM for things like balances storage because reader has to wait for writer in order to see the latest balance. If CHP really works this way(reader doesn't wait for writer) then does Java core provide a map implementation that uses things like ReadWriteLock for get and put operations? Something like when Map makes a get on specific segment then it acquires read lock on this segment which won't block other readers of this segment. And put will acquire write lock on this segment which will block readers of this segment


Solution

  • When both a reader and a writer attempt to access the same volatile location, one of two things will happen: either the reader will read the value and then the writer will update it, or the writer will first update the value and then the reader will read it.

    The same thing is also true if you use locks. A ReadWriteLock is unnecessary for reading a volatile value if writes are protected by a lock. Regardless of the synchronization method used, once a value is read it can be modified by another thread.

    For the scenario you describe (the balances), the critical section is read-operate-write, which needs a lock, or an atomic add.