I read in a book that read in ConcurrentHashmap
does not guarantee the most recently updated state and it can sometimes gives the closer value. Is this correct?
I have read its javadocs and many blogs which seems to say otherwise (i.e. it is accurate).
Which one is true?
Intuitively, a ConcurrentHashMap should behave like a set of volatile variables; map keys being the variable addresses. get(key)
and put(key, value)
should behave like volatile read and write.
That is not explicitly stated in the document. However, I would strongly believe that it is the case. Otherwise there will be a lot of unexpected, surprising behaviors that undermine application logic.
I don't think Doug Lea would do that to us. To be sure, someone please ask him on concurrency-interest
mailing list.
Suppose it does obey the volatile semantics, we can reason based on Java Memory Model -
All volatile reads and writes form a single total order. This can be considered a pseudo time line, where reads/writes are points on it.
A volatile read sees the immediate preceding volatile write, and sees only that write. "Preceding" here is according to the pseudo time line.
The pseudo time line can differ from "real" time line. However, in theory, a volatile write cannot be infinitely postponed on the pseudo time line. And, in pracitce, two time lines are pretty close.
Therefore, we can be pretty sure that, a volatile write should become visible "very quickly" to reads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With