Are empty synchronized blocks optimized by the Java compiler?

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

 synchronized(obj){ //No code here } 

Since the synchronized block does not contain any code, the JIT compiler optimizes it without blocking on obj , since it will be useless?

Does the Java compiler perform similar tricks, such as escalation blocking, but will this synchronized block be optimized as well?

EDIT:

According to the point made by assylias,

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

Now the JIT compiler will be able to optimize it, since I use an object that does not escape my method?

+4
source share
1 answer

This cannot be optimized based on the semantics of the Java Memory Model. The lock capture lock operation may be replaced by something else, but even an empty synchronized block has consequences for the visibility of actions taken by other threads acquiring the same lock.

In particular, there is a guarantee that all write operations performed by one thread, before releasing the lock, will be visible to another thread after it acquires the same lock.

Regarding your EDIT

This is a completely different case: a block is obtained at the object, which can be proved by analysis of the escape, which no other thread can ever extract. In this case, it does not matter what the contents of the synchronized block are: the point is used only in the used lock. The code may look like 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 may be affected by a transformation known as locking: the JVM may pretend to never see a synchronized block. This is because the semantics of JMM apply only to cases of acquiring the same lock.

+12
source

Source: https://habr.com/ru/post/1495297/


All Articles