Video in progress
While this method runs, other threads and the GC wait for a long time. What is the cause?
static long sum(int[] data) {
long total = 0;
for (int i = 0; i < data.length; i++) { // 500 million elements
total += data[i] * 31 ^ (data[i] >>> 3);
}
return total;
}
A loop with an int counter becomes a "counted loop" in the JIT and its safepoint poll may be removed. Then, when the GC wants to stop all threads, this thread doesn't reach a safepoint until the loop finishes, and the whole JVM waits.
📖 Answer
For a stop-the-world pause to begin, all Java threads have to reach a safepoint. In JIT-compiled code the safepoint check is at method return and on the backward jump of loops. But for a loop with an int index and a known bound (a counted loop), C2 used to be able to remove this check, for speed.
The result is this picture in the log: the GC itself takes 5 ms, but Reaching safepoint takes 800 ms. All the other threads stand still for that whole time.
To check:
-Xlog:safepoint=info
# ... Reaching safepoint: 812345678 ns, At safepoint: 4123456 ns
Since JDK 10 there is loop strip mining (together with -XX:+UseCountedLoopSafepoints): C2 splits the loop into inner chunks and puts a safepoint poll at the end of each chunk. In modern JDKs with G1, ZGC and Shenandoah this problem is much rarer (they turn the flag on themselves; with Parallel/Serial GC it is off by default), but it still shows up in old versions or with special flags.
There are other causes of time-to-safepoint too: copying or filling very large arrays (no poll inside intrinsics), pages that went to swap, CPU throttling in a container. A thread inside JNI does not make the safepoint wait. In practice I always measure the GC pause and the time to reach the safepoint separately, because they come from different causes.
Sign up to mark studied questions and save your progress.