Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I noticed a weird construct in ConcurrentHashMap's compute and computeIfAbsent methods:

Node<K,V> r = new ReservationNode<K,V>();
synchronized (r) {
  //...
}

What is the point of synchronizing on a local object considering that the JIT will most likely treat it as a no-op?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
129 views
Welcome To Ask or Share your Answers For Others

1 Answer

Right after the code has acquired the object’s monitor, the reference to the object is stored into the tab which is the globally visible array of nodes which make up the contents of the ConcurrentHashMap:

Node<K,V> r = new ReservationNode<K,V>();
synchronized (r) {
    if (casTabAt(tab, i, null, r)) {

Right at this point, other threads executing other modification methods on the same ConcurrentHashMap might encounter this incomplete node while traversing the global array, in other words, the Node reference has escaped.

While at the point where the ReservationNode has been constructed, there is no possibility for contention on a newly created object, in the other methods, which are synchronizing on Nodes found in the array, there might be contention for exactly that Node.

It’s like a “priority-synchronization”. The creator is synchronizing at a point where the reference has not been escaped yet therefore it is guaranteed to succeed while at the point where the reference escapes, all other threads will have to wait, in the unlikely (but still possible) event that they access exactly that Node.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...