What javac does
synchronized
monitorenter and monitorexit for a block; only a flag for a method.
A synchronized block compiles to monitorenter and monitorexit around its body, with a handler that unlocks the monitor if the body throws. A synchronized method compiles to nothing at all: the ACC_SYNCHRONIZED flag tells the JVM to take the lock on entry and release it on every exit.
The source
// synchronized: monitorenter and monitorexit for a block, only a flag for a method.
public class Sync {
private final Object lock = new Object();
private int count;
void increment() {
synchronized (lock) {
count++;
}
}
synchronized int get() {
return count;
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
- The lock object is stored in a hidden local (
astore_1), so the same object is unlocked even if the field is changed inside the block. - There are two
monitorexits: one on the normal path, and one in the handler, which then rethrows. - The handler's range also covers itself (the second line of the exception table), so the monitor is still released if something fails while unlocking.
get()contains no monitor instructions: it is thesynchronizedflag on the method that does the locking.
Sync.class
public Sync()
void increment()
synchronized int get()
javac --release 8 to 25 (the same bytecode for every release)