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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With