Reputation: 151
According to the ConcurrentMap
Javadoc:
Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a
ConcurrentMap
as a key or value happen-before actions subsequent to the access or removal of that object from theConcurrentMap
in another thread.
What is the meaning of above statement? And how does it work as the get()
method in ConcurrentHashMap
is not blocking (compared to BlockingQueue
for example)?
Upvotes: 5
Views: 350
Reputation: 1272
GhostCat already explained the meaning of happens-before. However, it might be worth noting the difference between this and "blocking".
In a blocking queue, a thread trying to poll from the queue will wait until something is available.
For something like a ConcurrentHashMap
, this is not the case. A happens-before relationship simple means that everything you did before adding it to the map has still happened when the other thread accesses it. But it doesn't mean the other thread will wait for something with the given key to be available.
To give an example where this is important, consider two classes foo and bar. In the constructor of Foo, we add it to a list in Bar. Now we put this instance of Foo in the ConcurrentHashMap
and access it in another thread. It is logical that everything we did to that instance of Foo has still happened. However, Java will also make sure that the instance of Foo has still been added to the list in Bar.
Upvotes: 2
Reputation: 140417
The meaning is rather simple. Assume you have two pieces of code:
a = new A();
b = ...
someConcurrentHashMap.put(b, whatever);
And then:
Whatever value = someConcurrentHashMap.get(b);
c = new C();
When b
is the same object and these two pieces of code are executed by two different threads, then it is guaranteed that a = new A()
happens before c = new C()
.
For further reading on "happens before" - see here.
For the implementation details I recommend you to study the source code - that contains tons of (non-javadoc!) comments that explain the inner workings of this class.
Upvotes: 5