According to JVM Specification, paragraph 3.14 Synchronization, JVM call monitorexit instruction twice.
I wonder why JVM need such behavior? Why do we call this instruction 2 times, but not 3 or 4 or N times?
May be it's somehow connected with types of synchronization locks?
The code is not "calling" the monitorexit
instruction twice. It is executing it once on two different code paths.
synchronized
block exits normally.You could write the bytecodes in the example as pseudo-code that looks like this:
void onlyMe(Foo f) {
monitorEntry(f);
try {
doSomething();
monitorExit();
} catch (Throwable any) {
monitorExit();
throw any;
}
}
If you want more information on this, take a look at this older question: