Memory Consistency Effects in ConcurrentMap

According to the ConcurrentMap

Javadoc
:

Memory consistency effects. As with other parallel collections, actions on a thread before placing an object in ConcurrentMap

as a key or value occur before actions after accessing or deleting that object from ConcurrentMap

on another thread.

What is the meaning of the above? And how does this work, since the method get()

in ConcurrentHashMap

does not block (for example, compared to BlockingQueue

)?

+3


source to share


2 answers


The meaning is pretty simple. Let's assume you have two codes:

 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 the two pieces of code are executed by two different threads , then it is guaranteed that what a = new A()

happens before c = new C()

.

For further reading "before" - see here .

For implementation details, I recommend checking out the source code - containing tons of (non-javadoc!) That explain the inner workings of this class.

+3


source


GhostCat has already explained the meaning of what happened earlier. However, it might be worth noting the difference between this and "blocking".

In a blocking queue, a thread trying to poll the queue will wait until something is available.



For something like ConcurrentHashMap

, it isn't. Origin-before relationship simply means that whatever you did before adding it to the map still happened when another thread accessed it. But that doesn't mean that another thread will wait for something with the supplied key.

To give an example where this matters, consider the two classes foo and bar. In the constructor of Foo, we add it to the list in Bar. Now we put this instance of Foo in ConcurrentHashMap

and get it on another thread. It makes sense that everything we did with this Foo example still happened. However, Java will also make sure that the Foo instance is still added to the list in Bar.

+1


source







All Articles