Video in progress
What is a safepoint, and can the application stall for a long time even when the pause in the GC log is short?
A safepoint is a state where all Java threads are stopped and the JVM can safely do its work. The pause has two parts: the time it takes to stop the threads (time-to-safepoint) and the work itself. If one thread stops late, all the others wait, and the GC log may show only the second part.
📖 Answer
The JVM does not stop threads by force. The threads themselves check at certain places (on method return, on a loop jumping back) "has a safepoint been requested?" and stop.
The classic trap is the counted loop:
long sum = 0;
for (int i = 0; i < hugeArray.length; i++) { // a loop with an int counter
sum += hugeArray[i];
}
C2 could remove the safepoint check from a loop like this (it has an int bound, so it "finishes quickly"). If the array is big, this thread doesn't stop for hundreds of milliseconds, and all the other threads wait for it at the safepoint. Since JDK 10, loop strip mining has mostly solved this for G1, ZGC and Shenandoah (they turn on UseCountedLoopSafepoints themselves; with Parallel and Serial GC it is off by default), but native code, a big System.arraycopy and some intrinsics can still cause delays.
It is not only the GC that requests a safepoint: deoptimization, revoking biased locking (in old JDKs), thread dumps, heap dumps and class redefinition do too.
Diagnostics:
-Xlog:safepoint=info:file=safepoint.log:uptime
For every safepoint the log has Reaching safepoint: X ns and At safepoint: Y ns. If the first is big, the problem is the late thread. The SafepointBegin/SafepointStateSynchronization events in JFR give the same information. -XX:+SafepointTimeout -XX:SafepointTimeoutDelay=100 helps you find the thread that was late.
Sign up to mark studied questions and save your progress.