Video in progress

Strong Middle ⚙️ JVM and memory

What is safepoint bias, and why do some profilers send you to the wrong method?

Some profilers take a stack sample only when the thread has stopped at a safepoint. So they point at places that have a safepoint check (the end of a loop, a method return), and the real hot code stays invisible. async-profiler and JFR are mostly free of this problem.

📖 Answer

Old sampling profilers built on JMX's getThreadInfo or jstack (VisualVM's sampler is close to that) ask the JVM for the stacks of all threads at every sample. That requires a safepoint. The thread doesn't stop right in the middle of a computation, it keeps running until the next safepoint poll.

As a result:

  • a hot loop that is inlined and has had its safepoint check removed may not be visible at all;
  • the method that comes after it turns out to be the "heaviest";
  • every sample calls a safepoint and slows down the application itself.

On one project the profiler pointed at JSON serialization, when in fact the time went into a hand-written hash computation loop just before it. When we moved to async-profiler the picture changed completely.

The tools that are free of it:

  • async-profiler: stops a thread at any point through Linux perf_events or a signal and takes the stack with AsyncGetCallTrace. It also shows native and JVM internal frames;
  • JFR: jdk.ExecutionSample doesn't depend on safepoints either, the overhead is low, and you can leave it on permanently on prod.

One note: no profiler is perfect. Inlined methods may not show up as a separate frame, or there are cases where the stack can't be unwound. That is why I confirm a profile's conclusion with a small change and a re-measurement.