Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing on local variable

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?

like image 280
assylias Avatar asked Oct 21 '14 08:10

assylias


People also ask

What are synchronization variables?

Synchronization variables are synchronization primitives that are used to coordinate the execution of processes based on asynchronous events. When allocated, synchronization variables serve as points upon which one or more processes can block until an event occurs. Then one or all of the processes can be unblocked.

How do you synchronize variables?

Use the synchronized keyword. Using the synchronized keyword on the methods will require threads to obtain a lock on the instance of sample . Thus, if any one thread is in newmsg() , no other thread will be able to get a lock on the instance of sample , even if it were trying to invoke getmsg() .

Can we make a variable synchronized?

You can have both static synchronized method and nonstatic synchronized method and synchronized blocks in Java but we can not have synchronized variable in java. Using synchronized keyword with a variable is illegal and will result in compilation error.


1 Answers

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.

like image 90
Holger Avatar answered Sep 29 '22 12:09

Holger