Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are empty synchronized blocks optimized out by Java compiler?

Suppose somewhere in my code I write an empty synchronized block:

synchronized(obj){
   //No code here
}

So as the synchronized block does not contain any code, will JIT compiler optimize that out by not locking on obj as it will be of no use?

Java compiler does similar tricks such as Lock coarsening but will this synchronized block be also optimized out?

EDIT:

As per the point made by assylias,

synchronized(new Object()){
   //empty block
}

will the JIT compiler now be able to optimize this out, since I am using an Object which doesn't escape my method?

like image 873
Narendra Pathai Avatar asked Aug 05 '13 10:08

Narendra Pathai


1 Answers

This can't be optimized away on the basis of the Java Memory Model semantics. The lock acquisition-release operation may be replaced by something else, but even an empty synchronized block has consequences on the visibility of actions taken by other threads acquiring the same lock.

Specifically, there is a guarantee that all write actions done by one thread before releasing the lock are visible to the other thread after it acquires the same lock.

Regarding your EDIT

This is a very different case: a lock is obtained on an object which can be proved by escape analysis that no other thread will ever be able to fetch it. In this case it doesn't matter what the contents of the synchronized block are: the point is only in the lock used. The code can look as you posted it, or even like this:

Object o = new Object();
synchronized(o) { 
   // any operations you like, as long as they don't let o escape the method scope
}

This can be acted upon by the transformation known as lock elision: the JVM can pretend it never saw the synchronized block. This is because the JMM semantics refer only to the cases of acquiring the one and the same lock.

like image 191
Marko Topolnik Avatar answered Oct 04 '22 03:10

Marko Topolnik