Sub topic 3
Sampling and instrumentation: how profilers work
This chapter assumes you can run Java programs from the command line, read stack traces, and know that the JVM runs several threads over one shared heap. You do not need any profiler experience. The goal is a working model of how a profiler gets its numbers. That model explains which numbers you can trust, and it tells you which tool to pick for a given question.
What a profiler has to answer
A profiler answers one question: where does the program spend its resources? The resource is usually CPU time. It can also be memory allocation, time spent waiting on locks, or time spent in I/O.
A running JVM executes millions of method calls per second. A profiler cannot record every one without slowing the program down. Every profiler therefore makes a trade-off between detail, overhead and accuracy. The two main designs make that trade-off in opposite directions.
Sampling profilers
A sampling profiler interrupts the program at intervals and records what each thread is doing. The record is a stack trace for each thread, taken at one instant. The profiler then counts how often each method appears in those traces.
If a method shows up in 40 of 100 samples, the program spent roughly 40% of its sampled time in that method. The counts are statistical estimates, not exact measurements.
Strengths of sampling
- Overhead is low and controllable. A longer interval means fewer samples and less work.
- Overhead does not grow with the number of method calls. A tight loop calling a tiny method a billion times costs the same to sample as a quiet loop.
- It works on an unmodified application, so it is suitable for production.
Weaknesses of sampling
- Short methods can be missed. A method that runs for 50 microseconds may never be caught by a 10 ms interval.
- You get no exact call counts. A sample shows that a method was running, not how many times it was called.
- You need enough samples. With only 20 samples, a reading of 10% could easily be 3% or 20% in reality. Run the profile long enough to collect hundreds or thousands of samples.
- The sampling position can be biased. Some tools can only take a snapshot when all threads reach a safe point in the code. That bias gets its own chapter later in this tutorial.
Instrumenting profilers
An instrumenting profiler changes the code. It inserts extra instructions at method entry and exit, usually by rewriting bytecode when classes load. The inserted code records a timestamp and a counter each time the method is called.
Conceptually, instrumentation turns this:
int compute(int x) {
return x * x + 1;
}into something like this:
int compute(int x) {
Profiler.enter("compute");
try {
return x * x + 1;
} finally {
Profiler.exit("compute");
}
}The Profiler.enter and Profiler.exit calls are illustrative. Real tools generate equivalent bytecode rather than source.
Strengths of instrumentation
- Call counts are exact.
- Even very short methods are recorded.
- Timing for a specific method can be exact for that method, within the limits of the clock.
Weaknesses of instrumentation
- Overhead is high. The added work can be larger than the work in a small method. A method that took 5 ns now takes 50 ns or more.
- Overhead is uneven. Small, frequently called methods slow down far more than large ones, so the profile exaggerates their share.
- The inserted code changes what the JIT compiler can do. Inlining decisions and other optimizations differ, so you may be measuring a program that behaves differently from the real one.
- Instrumenting everything produces enormous data. In practice you instrument only selected classes.
Comparing the two approaches
| Property | Sampling | Instrumentation |
|---|---|---|
| Overhead | Low, set by the interval | High, grows with call count |
| Call counts | Estimated at best | Exact |
| Short methods | May be missed | Always seen |
| Distorts JIT behavior | Little | Often a lot |
| Suitable for production | Yes | Rarely |
| Best question | Where is the time going? | How many times, and from where? |
A good default is to start with sampling. Use instrumentation on a small, targeted area once sampling has pointed you there and you need exact counts.
What JFR does
Java Flight Recorder (JFR), built into the JDK, is mostly a sampling system. For CPU and execution samples, it records stack traces of running Java threads at a fixed interval. The default interval is 20 ms. The profile settings use 10 ms.
JFR also records events, which are not samples. Examples are garbage collections, lock waits above a threshold, file reads, and object allocations outside thread-local buffers. These are recorded when they happen, so the JVM itself provides the data with very low overhead.
This mix is why JFR is practical in production. You get statistical CPU data at a small cost, plus accurate event data for the things the JVM already tracks.
Sampling is a statistical claim
Think of a sample as a poll. A poll of 1,000 people gives a useful estimate of an election, but a poll of 10 people does not. The same rule applies here.
Two practical consequences follow.
- Profile under a realistic load. If the program is idle, the samples describe idle behavior.
- Profile long enough. For a hot spot that uses 5% of the time to be visible and stable, you need thousands of samples. At a 10 ms interval and one thread, that is a few minutes.
You can see the effect with a deliberately slow program. The following one concatenates strings in a loop. Each s += i creates a new string and copies the old content, so the cost grows with the length of s.
import java.util.ArrayList;
import java.util.List;
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");
}
}This program has a clear hot spot. A sampling profiler would show nearly all samples in main, in the string concatenation code and in the memory allocation and copying beneath it. Nothing here needs exact call counts, so sampling is the right tool. An instrumenting profiler would add overhead to every call, and it would not tell you anything new.
To record it with JFR, compile and run the class with a recording option:
javac Slow.java
java -XX:StartFlightRecording=duration=60s,filename=app.jfr,settings=profile SlowThe program finishes in a few seconds, and JFR writes app.jfr when the JVM exits. The next chapters show how to open and read that file.
Failure modes to watch for
- Observer effect. Any profiler changes the program it measures. Sampling does it slightly, and instrumentation does it heavily. If a result looks surprising, check it with a second method.
- Inlining hides methods. The JIT compiler can merge a small method into its caller. Good profilers use debug information to show the original methods. Tools without it may attribute time to the caller.
- Idle or waiting threads. A sampler that records all threads will show many samples in
Object.waitor in socket reads. These are not CPU use. Check whether the profile is CPU time or wall-clock time before drawing conclusions. - Too short a run. At the start of a run, the JIT compiler is still compiling, so early samples show interpreter behavior. A later chapter covers warmup.
Choosing between them
Ask what you need to know.
- If the question is "where is the time going?", use sampling.
- If the question is "how often is this method called?", use instrumentation on that method, or a JFR event.
- If the program is in production, use sampling or JFR events only.
- If the two disagree, suspect the instrumentation first. It is the one that changes the program more.
Exercise
A service has a method that takes 2 microseconds and is called 5 million times per second. You need to know whether it dominates CPU time. Which profiler type would you use first, and why might an instrumenting profiler give a misleading answer?
Show answer
Use a sampling profiler first. Its overhead does not depend on the call count, so the program behaves almost normally, and if the method uses a lot of CPU it will appear in many samples. An instrumenting profiler adds entry and exit code to a method that is itself only 2 microseconds long. The added work can be as large as the method's own work, so the method would look more expensive than it is, and the changed code may also prevent the JIT from inlining it.
Exercise
You record a 5-second sampling profile at a 20 ms interval on one busy thread. How many samples do you expect, and why is a method with 3 samples a weak finding?
Show answer
About 250 samples (5000 ms divided by 20 ms). Three samples is about 1.2% of the total, and with so few counts the true share could differ a lot from that number just by chance. Run longer or at a shorter interval, and see whether the method stays visible.