This example works fine (prints true) when I run it with -XX:+DoEscapeAnalysis -server:
final Object lock = new Object();
synchronized (lock) {
System.out.println(Thread.holdsLock(lock)); // prints true
}
On the other hand, the short and not too detailed Java HotSpotâ„¢ Virtual Machine Performance Enhancements documentation says the following:
The server compiler also eliminates locks for all non-globally escaping objects.
So, if escape analysis eliminates the unnecessary synchronization here it should print false.
I guess escape analysis handles holdsLock properly (eliminates locks does not broke holdsLock()) but I would like to see some official reference or maybe relevant JVM source code snippets.
Thread.holdsLockis a native method in JDK, and it is not a JVM intrinsic.This means, the implementation of
Thread.holdsLockis a black box for JIT compiler. Since this method acceptslockas an argument,lockcan no longer be considered as a local non-escapable object. JVM knows for sure, thatlockdoes escape, so neither allocation nor synchronization may be eliminated in this example.But, as @Holger noticed, even if
holdsLockwas a JVM intrinsic, it should never returnfalse, otherwise this would be a specification violation. No JVM optimization may break the correctness of a program.