Sub topic 2
Warmup and JIT compilation
This chapter explains why the first seconds of a JVM program behave differently from the rest, and why that matters for any timing you take. It assumes you know basic Java and Maven, and that the JVM compiles hot code while the program runs. Here you will see the mechanism in detail, run a small experiment, and learn the errors it causes in measurements.
The JVM does not run your code at one speed
A Java program does not start as machine code. The JVM first runs your bytecode in an interpreter. The interpreter is simple and starts quickly, but it is slow per operation. While it runs, the JVM counts how often each method is called and how often each loop jumps back.
When a method or loop becomes hot, the JVM compiles it to machine code with the JIT (just-in-time) compiler. HotSpot, the common JVM, has two compilers:
- C1 compiles quickly and produces moderately fast code. It can add profiling code to gather data.
- C2 compiles slowly and produces highly optimized code. It uses the profile data that was collected earlier.
HotSpot uses tiered compilation by default. Code moves up through levels as it proves itself hot.
| Tier | Executor | Typical speed | Notes |
|---|---|---|---|
| 0 | Interpreter | Slowest | Collects invocation and loop counts |
| 1 to 3 | C1 compiled code | Medium | Level 3 includes full profiling |
| 4 | C2 compiled code | Fastest | Uses the profile for aggressive optimization |
The thresholds are measured in thousands of invocations or loop iterations. The exact numbers vary by JVM version and flags, so treat them as a rough scale and not a contract.
Why the optimizer is fast and fragile
C2 is quick because it makes assumptions based on what it has observed so far. Common optimizations include:
- Inlining. The body of a small method is copied into its caller. This removes call overhead and exposes more code to other optimizations.
- Escape analysis. If an object never leaves a method, the JVM may avoid allocating it on the heap.
- Loop optimizations. Loops can be unrolled, and bounds checks can be removed.
- Speculation on types. If a call site has only ever seen one class, the JVM can call that class's method directly.
Each assumption is a bet. If the program later behaves differently, for example a second class shows up at that call site, the JVM throws away the compiled code. This is called deoptimization. The code runs in the interpreter again and is recompiled later with updated knowledge.
This has an important consequence. The speed of a piece of code depends on what ran before it. The profile collected earlier in the process shapes the machine code that is generated.
Warmup is the period before steady state
Warmup is the time during which code is still being interpreted, compiled or recompiled. During warmup the measured speed is not the speed you will have in a long-running service. Once compilation settles, the program reaches steady state, where timings are stable.
Other things also change during warmup:
- Classes are loaded and initialized the first time they are used.
- The heap grows and the garbage collector adapts its sizing.
- CPU caches and branch predictors fill with relevant data.
- JIT compilation runs on background threads, so it competes with your code for CPU time.
A benchmark that measures during warmup measures a mixture of interpreted code, partly optimized code and compiler overhead. The result depends on when you start the clock.
Seeing warmup yourself
The following program times the same work in repeated rounds and prints each round. It is a teaching tool. It is not a good way to benchmark, and the next chapters explain why.
public class WarmupDemo {
static long work(int[] data) {
long total = 0;
for (int value : data) {
total += value % 7;
}
return total;
}
public static void main(String[] args) {
int[] data = new int[100_000];
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
long sink = 0;
for (int round = 1; round <= 15; round++) {
long start = System.nanoTime();
for (int i = 0; i < 100; i++) {
sink += work(data);
}
long elapsed = System.nanoTime() - start;
System.out.printf("round %2d: %,d ns%n", round, elapsed);
}
System.out.println("sink = " + sink);
}
}Compile and run it:
javac WarmupDemo.java
java WarmupDemoOn a typical machine the first rounds are several times slower than the later ones, and then the numbers flatten out. The exact figures differ between machines, so do not expect to match any particular output. The pattern is what matters: early rounds are slow, later rounds are fast and close together.
You can watch the compiler directly. The flag -XX:+PrintCompilation prints a line each time a method is compiled:
java -XX:+PrintCompilation WarmupDemoLook for lines that mention WarmupDemo::work. You will usually see it compiled at a low tier first and then at tier 4. If you see the text made not entrant, that marks code being discarded, which is often a deoptimization or the replacement of a lower-tier version by a higher one.
On-stack replacement
A method that is called once but contains a long loop poses a problem. It never gets called again, so the JVM cannot switch to compiled code at the next call. HotSpot solves this with on-stack replacement (OSR). It compiles the loop and switches from interpreted to compiled code in the middle of the running method.
OSR code is not always as good as code compiled for a normal method entry. This is one reason a benchmark written as one huge main method with a long loop can behave differently from the same code in a small method called many times. In PrintCompilation output, OSR compilations are marked with a % character.
How warmup breaks hand-written timing
Several problems follow from the mechanism above.
- Timing too early. If you time the first few calls, you measure the interpreter and C1.
- Timing across the transition. If compilation happens in the middle of your timed region, the average mixes slow and fast operations. A single number hides this.
- Profile pollution. If one process runs benchmark A and then benchmark B, the profile from A can influence the code generated for B. For example, a shared helper method may have seen two types by the time B runs, so it cannot be inlined as aggressively.
- Unrepresentative steady state. Even a long warmup may reach a state that depends on the order of the code you ran.
- Background noise. Compiler threads and the garbage collector use CPU while you measure.
Common mistakes
- Assuming that a single warmup loop is enough. Warmup of one method does not guarantee that the code you measure is fully optimized. Other methods it calls may still be compiling.
- Warming up with different inputs than you measure. If warmup uses small arrays and measurement uses large ones, the profile may not match, and the JVM may recompile during measurement.
- Running several experiments in one JVM and trusting the later ones. Earlier experiments leave profile data and heap state behind.
- Treating the first run as the truth about production. A long-running server mostly lives in steady state, so steady-state numbers matter more. A command-line tool that exits in a second mostly lives in warmup, so there the warmup cost is the number that matters. Decide which one you are measuring before you start.
- Ignoring the machine. Frequency scaling, other processes and thermal limits also change timings. Warmup is one source of variance among several.
What this means for the design of a benchmark harness
The mechanism points to the requirements of a trustworthy harness:
- It must run the code long enough before measuring, so the JIT reaches a stable state.
- It must measure in several separate intervals, so you can see whether the numbers are stable.
- It must start fresh JVM processes more than once, so one unlucky profile does not decide the result.
- It must keep the compiler from removing the work being measured.
The following chapters on JMH cover each of these. Warmup iterations, measurement iterations and forks, which you will configure later with @Warmup, @Measurement and @Fork, are direct answers to the behavior shown in this chapter.
Exercises
Exercise
You run WarmupDemo with -XX:+PrintCompilation and see the line for work compiled at tier 3, followed later by a line for work compiled at tier 4. What does this tell you about the speed of rounds 1, 5 and 15, and which round would you trust as a steady-state figure?
Show answer
Early rounds run in the interpreter and then in tier 3 (C1) code, so they are slowest. After the tier 4 (C2) version is installed, rounds run at full speed. Round 15 is the most trustworthy, but only if the round times have flattened out. You should check that the last several rounds are close to each other before trusting any one of them.
Exercise
A colleague benchmarks method A and method B in the same JVM, A first. B is slower in the result. Name one reason the order of the runs could have caused this, other than B being slower in itself.
Show answer
A shared method used by both may have seen types or branches from A, so the profile no longer fits B. The JIT then produces less aggressive code, for example with less inlining, for B. Running each benchmark in its own fresh JVM avoids this, which is what forks do in JMH.