Sub topic 3
Sampling and instrumentation: how profilers work
This chapter assumes you can run Java from the command line, read stack traces, and know that a JVM runs several threads over a shared heap. You do not need any profiler installed yet.
Two ways to watch a program
A profiler answers the question "where does the time go?" It can answer in two basic ways.
- Sampling looks at the program at intervals. Every few milliseconds the profiler captures the stack trace of each running thread. A method that shows up in 40% of the samples is probably using about 40% of the time.
- Instrumentation changes the program. The profiler inserts extra code at method entry and exit (bytecode rewriting, usually through a Java agent). Each call is then counted and timed exactly.
Trade-offs
| Property | Sampling | Instrumentation |
|---|---|---|
| Overhead | Low and tunable by the sampling interval | Often high, and it grows with call count |
| Accuracy of counts | Statistical estimate | Exact |
| Short methods | May be missed | Always recorded |
| Distortion | Small | Can be large |
| Suitable for production | Yes | Rarely |
Instrumentation distorts what it measures. A tiny method that runs in 20 nanoseconds can gain more time from the timing code than from its own work. The JIT compiler may also inline it differently once it is instrumented, so you end up measuring a program that behaves differently from the real one. Sampling avoids this, but it has errors of its own.
Sampling errors
Sampling is statistical, so a short run gives noisy results. With a 20 ms interval, a 2-second run yields only about 100 samples per thread. A method showing 3 samples is not clearly different from one showing 5. Run long enough to collect thousands of samples before you trust small percentages.
A second error is bias. Some profilers can only take a snapshot when a thread reaches a safepoint, a point where the JVM can pause it safely. Code that runs between safepoints is then under-reported. A later chapter covers this in detail. Java Flight Recorder (JFR) avoids that restriction, which is a main reason it is the default tool in this tutorial.
A target to profile
Here is a program with an obvious hot spot. Each s += i copies the whole string built so far.
public class Slow {
public static void main(String[] args) {
long start = System.nanoTime();
for (int round = 0; round < 200; round++) {
String s = "";
for (int i = 0; i < 5_000; i++) {
s += i;
}
if (s.length() == 0) {
System.out.println("unreachable");
}
}
System.out.println((System.nanoTime() - start) / 1_000_000 + " ms");
}
}A sampling profiler would show most samples inside main, in string concatenation and array copying code. An instrumenting profiler would report exactly 1,000,000 concatenations, but the program would run much slower while it counted them.
Choosing between them
- Use sampling first. It is cheap, needs no code changes, and finds the large costs.
- Use instrumentation when you need exact call counts, for example to confirm a method runs once per request instead of 50 times.
- Always check overhead. If the profiled run is much slower than a normal run, the numbers describe the profiler as much as your code.
Exercise
A method named parse appears in 2 of 100 samples, taken during a 2-second run. Why should you hesitate to conclude that parse takes 2% of the time, and what would you do next?
Show answer
100 samples is too few for a reliable estimate, so the real share could be well above or below 2%. Run the workload longer, or lower the sampling interval, until you have thousands of samples, then check whether parse still shows a similar share.