Are empty synchronized blocks optimized out by Java compiler?

让人想犯罪 __ 提交于 2019-11-30 04:49:47

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18056111/are-empty-synchronized-blocks-optimized-out-by-java-compiler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!