Reputation: 1558
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?
Upvotes: 6
Views: 1164
Reputation: 19682
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.
Upvotes: 1
Reputation: 158
From ConcurrentHashMap
javadoc:
Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.
One point to highlight is that an Iterator
is not going to reflect changes that are made after the Iterator
is created. So if you need to iterate over the values of the map, while other threads are adding to the map, and you care about the most current state of the map, then using a ConcurrentHashMap
may not be the implementation of map that you need.
Upvotes: 1
Reputation: 6716
That is the nature of concurrency. Any concurrent collection may give you the old value in a field if a currently pending write operation is not safely finished. That is in all cases what you have to expect. The collections made for concurrency will not give you corrupted values or break if you access them from multiple threads, but they may give you old values, if writing is not done.
Upvotes: 0