Is there a cheaper method call in Java 9+ which keeps its safepoint?
The JVM removes safepoints at runtime to improve efficiency however this can make profiling and monitoring the code more difficult. For this reason, we deliberately add trivial calls in carefully selected places to ensure there is a safepoint present.
public static void safepoint() {
if (IS_JAVA_9_PLUS)
Thread.holdsLock(""); // 100 ns on Java 11
else
Compiler.enable(); // 5 ns on Java 8
}
public static void optionalSafepoint() {
if (SAFEPOINT_ENABLED)
if (IS_JAVA_9_PLUS)
Thread.holdsLock("");
else
Compiler.enable();
}
On Java 8 this overhead is fine, but Compiler.enable()
gets optimised away in Java 9+ so we have to use a much more expensive method, or not enable this feature.
EDIT: Apart from profilers, I have used the safepoint()
to get better detail from Thread.getStackTrace()
so the application can profile itself e.g. when it takes too long to perform an action.