Sub topic 9
Why some profilers mislead: safepoint bias
This chapter assumes you can read a stack trace, know that the JVM has a heap, garbage collector and JIT compiler, and have seen a sampling profiler's output (a list of hot methods). It explains why a profiler can name the wrong method as the hot spot, and how to avoid that.
The problem in one picture
A sampling profiler periodically asks "what is each thread doing right now?" and counts the answers. If the answers are a fair random sample of where time goes, the counts point at the real bottleneck. If the answers are skewed, the profiler confidently reports a method that is not slow.
Safepoint bias is one such skew. It happens when a profiler can only take a sample at certain places in the code, and those places are not spread evenly across the time your program spends.
What a safepoint is
A safepoint is a point in the execution of a thread where the JVM knows exactly what the thread's state is: which stack slots and registers hold object references, and which frame is on top. The JVM needs this knowledge to do certain work safely.
Work that needs all threads at a safepoint includes:
- Most garbage collection phases that pause the application.
- Deoptimization and some code cache changes.
- Biased-lock revocation in older JDKs, and class redefinition.
- Taking a thread dump with
jstackorjcmd Thread.print.
To reach a safepoint, the JVM sets a flag. Each running thread checks the flag at specific places and parks itself when it sees it set. Compiled code contains these checks (called safepoint polls) in these places:
- On method returns.
- On the back edge of loops that are not "counted" loops (a counted loop is an
intloop with a simple, bounded index, which the JIT may optimize to remove the poll).
Between polls, a thread cannot stop. The JVM waits for it.
How this biases a profile
A safepoint-based profiler uses the same mechanism as a thread dump. It brings threads to a safepoint, reads their stacks, and resumes them. The older JVMTI call GetAllStackTraces works this way, and many classic profilers and some IDE sampling modes are built on it.
Three things go wrong:
- Samples land only at polls. Code between polls never appears as the top frame, no matter how much CPU it uses. Time spent in a tight counted loop is credited to whatever method contains the next poll, often the caller after the loop returns.
- The delay is not random. The longer a stretch of code runs without a poll, the more likely the safepoint request arrives during it, and the more time passes before the sample. So the long stretches are not undercounted evenly. They are shifted onto the poll that ends them.
- Sampling itself changes the program. Each sample stops every thread. A high sample rate adds pauses that you then measure as part of the application. Native code and some JIT-inlined frames can also be attributed to the wrong frame.
Here is a concrete example. The method sum below does the real work, but it contains only a counted loop. The method that calls it returns, so it has a poll.
public class BiasDemo {
static long sum(int[] data) {
long total = 0;
for (int i = 0; i < data.length; i++) {
total += data[i] * 31L;
}
return total;
}
static long caller(int[] data) {
long result = 0;
for (int round = 0; round < 200; round++) {
result += sum(data);
}
return result;
}
public static void main(String[] args) {
int[] data = new int[50_000_000];
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
long start = System.nanoTime();
long r = caller(data);
System.out.println(r + " in " + (System.nanoTime() - start) / 1_000_000 + " ms");
}
}The real hot spot is the total += ... line in sum. A safepoint-biased profiler may instead report the line after the loop, the return from sum, or part of caller, because those are the places where a poll exists. The report looks plausible, which is the danger: you would optimize the wrong method.
If sum is inlined into caller, the loop can also lose its poll entirely. Then a single request for a safepoint may wait for the whole 200-round computation to finish. This is a known cause of long "time to safepoint" pauses that stall every other thread, including during GC.
Checking for the problem in your own JVM
You can see how long threads take to reach a safepoint using unified logging.
java -Xlog:safepoint*:file=safepoint.log:time,uptime -jar app.jarEach safepoint log line reports how long the JVM spent reaching the safepoint and how long it stayed there. Large "reaching safepoint" times are a sign that some thread runs long stretches without polls. In that case a safepoint-based profiler will be especially misleading for your program.
What fixes it
Modern profilers avoid the safepoint requirement. Two approaches are common:
- AsyncGetCallTrace. An internal HotSpot call that can read a thread's stack at any instruction, without stopping at a safepoint. Async-profiler uses it, together with an OS signal such as
SIGPROFor perf events, to interrupt threads wherever they are. - JFR's own sampler. Java Flight Recorder samples running threads on a timer, by default about every 10 or 20 ms depending on settings, and walks the stack of each from outside the thread, without waiting for a poll. The JFR sampler is not constrained to safepoints, so it does not have this bias.
These methods are still not perfect. They need debug information to map an arbitrary instruction back to a line of code. HotSpot only keeps that detail at certain points in compiled code, so the profiler may snap the sample to the nearest recorded location. This is much finer than safepoint polls but can still shift attribution slightly within a method. HotSpot can add more debug information with -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints, which makes the line attribution more accurate at a small cost. Use that flag when you need precise lines inside hot loops.
| Profiler type | Where it can sample | Safepoint bias | Notes |
|---|---|---|---|
| JVMTI `GetAllStackTraces` based | Safepoints only | Yes | Pauses all threads each sample |
| JFR execution sampler | Any point in running code | No (small attribution error) | Low overhead, built in |
| Async-profiler (AsyncGetCallTrace) | Any point, signal driven | No (small attribution error) | Can also show native frames |
| Instrumenting profiler | At inserted probes | Different bias | Probes distort inlining and timing |
A practical cross-check
Use this routine whenever a profile points at a method that seems cheap.
- Record with JFR using
settings=profile. - Compare the top frames against the output of your first profiler.
- If they disagree, rerun with
-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints. - Make one change in the method the unbiased profiler names, and measure again with the same workload.
Exercise
A profiler shows that 70% of samples are in a method finish() that only returns a value, while the loop in the method above it does all the work. Name the likely cause, one way to confirm it, and one way to get a better profile.
Show answer
The likely cause is safepoint bias: the profiler can only sample at safepoint polls, and the long counted loop in the caller has no poll, so its time is credited to the next poll, such as the return in finish(). To confirm, run with -Xlog:safepoint* and look for long times to reach a safepoint, or compare with a profiler that does not use safepoints. For a better profile, use JFR or async-profiler, and add -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints for accurate line numbers.
Exercise
Why does a safepoint-based profiler tend to blame the method that contains a poll rather than the method that runs for a long time without one?
Show answer
A thread can stop only at a poll. When the profiler requests a sample, a thread in a long poll-free stretch keeps running until it reaches the next poll. The stack is then read there, so the time spent in the poll-free code is credited to the location of that poll.