Video in progress

Strong Middle ⚙️ JVM and memory

How do sampling and instrumenting profilers differ, and when do you use each?

A sampling profiler takes snapshots of thread stacks every N milliseconds: low overhead, usable on prod, but the result is statistical. An instrumenting profiler adds code at every method entry and exit: call counts are exact, but the overhead is large and it makes small methods behave differently from how the JIT would run them. I look for CPU problems with sampling, and for exact call counts with instrumentation.

📖 Answer

Sampling (async-profiler, JFR, VisualVM sampler):

  • every 10 ms it asks "which method are you in right now?";
  • if JsonParser.parse is in 300 of 1000 samples, about 30% of the time is spent there;
  • overhead 1-3%, doesn't change the code, doesn't touch the JIT's optimizations;
  • the downside: very short, rarely called methods may be invisible, and it doesn't tell you how many times something was called.

Instrumenting (VisualVM's profiler mode, the tracing mode of JProfiler/YourKit, a manual Micrometer Timer):

  • timer code is added at the start and the end of every method;
  • exact: validate() was called 1.2 million times, an average of 3 µs;
  • but if you add a 100 ns measurement to a 50 ns getter, the result is distorted. Inlining and escape analysis stop working, and you are measuring a different program;
  • 2-10 times overhead, unusable on prod.

When to use what:

  • "where is the CPU going?": sampling, a flame graph. 95% of the time this is enough;
  • "why is this request making 400 DB calls?": you need call counts, so tracing (OpenTelemetry spans) or targeted instrumentation;
  • "which method allocates how much?": async-profiler -e alloc or JFR allocation sampling, which is also sampling.

Put instrumentation only on the suspect package or method, not on the whole application. And when choosing a sampling profiler, take one free of safepoint bias, otherwise even the statistical result is wrong.