Search code examples
javajvmescape-analysis

Does escape analysis handles Thread.holdsLock() properly?


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.


Solution

  • Thread.holdsLock is a native method in JDK, and it is not a JVM intrinsic.

    This means, the implementation of Thread.holdsLock is a black box for JIT compiler. Since this method accepts lock as an argument, lock can no longer be considered as a local non-escapable object. JVM knows for sure, that lock does escape, so neither allocation nor synchronization may be eliminated in this example.

    But, as @Holger noticed, even if holdsLock was a JVM intrinsic, it should never return false, otherwise this would be a specification violation. No JVM optimization may break the correctness of a program.