Sub topic 16
Warmup and Benchmarking Pitfalls
This chapter assumes you know the interpreter, the C1 and C2 compilers, the tiers, -XX:+PrintCompilation, and deoptimization from earlier chapters. It applies them to one practical problem: measuring Java code without fooling yourself.
Why the first seconds are different
A JVM does not run at full speed from the start. A method begins in the interpreter (tier 0). It moves to C1 code with profiling, and later it may reach C2 code (tier 4). Each step changes how fast the method runs.
Warmup is the period before the hot code has reached its final compiled form. During warmup:
- Bytecode is interpreted, which is much slower than compiled code.
- Profiling code in tiers 2 and 3 adds overhead.
- The compile queue may hold many pending requests, so a hot method can wait for a compiler thread.
- Classes are still loading and initializing.
- The code cache and caches such as inline caches are still filling.
The steady state is the period after the important methods reach tier 4 and no more deoptimizations occur. A benchmark that mixes warmup and steady state measures neither one well.
Seeing warmup directly
The simplest way to see warmup is to time the same work repeatedly in one JVM and print each result.
public class WarmupTimer {
static int square(int x) {
return x * x;
}
static long work() {
long sum = 0;
for (int i = 0; i < 20_000_000; i++) {
sum += square(i % 1000);
}
return sum;
}
public static void main(String[] args) {
long sink = 0;
for (int round = 1; round <= 10; round++) {
long start = System.nanoTime();
sink += work();
long micros = (System.nanoTime() - start) / 1_000;
System.out.println("round " + round + ": " + micros + " us");
}
System.out.println("sink=" + sink);
}
}Compile and run it with the flags from the earlier chapters:
javac WarmupTimer.java
java WarmupTimer
java -Xint WarmupTimer
java -XX:TieredStopAtLevel=1 WarmupTimerTypical results, though exact numbers vary by machine:
- With default flags, round 1 is clearly slower than later rounds. Later rounds settle to a stable, lower time.
- With
-Xint, every round is slow and nothing improves, because nothing is ever compiled. - With
-XX:TieredStopAtLevel=1, the rounds settle quickly, but at a time that may be higher than C2 reaches for code that benefits from profile-based optimization.
Round 1 here is partly compiled through on-stack replacement (OSR), because work contains a long loop that runs before the method returns even once. Run with -XX:+PrintCompilation to see the % marker for those OSR compilations alongside the tier numbers.
Pitfall 1: timing a single run
Measuring one call of a method measures mostly the interpreter and the compile pipeline. The result also changes from run to run, because compile timing depends on thread scheduling and machine load.
A single cold measurement is valid in one case: you care about startup or first-request latency. Then cold is the right thing to measure, and you should say so. In every other case, run the code until it is warm before you record anything.
Pitfall 2: dead code elimination
C2 removes work whose result is never used. If your benchmark computes a value and throws it away, the compiler may delete the computation, and you then measure an empty loop.
public class DeadCode {
static double compute(int n) {
double r = 0;
for (int i = 1; i <= n; i++) {
r += Math.sqrt(i);
}
return r;
}
static double sink;
public static void main(String[] args) {
for (int round = 0; round < 5; round++) {
long start = System.nanoTime();
for (int i = 0; i < 2_000; i++) {
compute(10_000); // result ignored: may be removed
}
long ignored = System.nanoTime() - start;
start = System.nanoTime();
for (int i = 0; i < 2_000; i++) {
sink += compute(10_000); // result is kept
}
long kept = System.nanoTime() - start;
System.out.println("ignored=" + ignored / 1_000
+ " us, kept=" + kept / 1_000 + " us");
}
}
}Whether the first loop is fully removed depends on what the JIT can prove. Math.sqrt has no side effects, so removal is plausible. Treat any benchmark number that looks impossibly fast as a sign of dead code elimination. The defense is to consume every result, for example by accumulating into a field that is read at the end, or by passing it to a "black hole" provided by a benchmark harness.
Pitfall 3: constant folding
If the inputs are compile-time constants, the compiler may compute the answer once and never run your code. compute(10_000) with a literal argument is a candidate. Pass values that come from a field that is not final, from command-line arguments, or from a harness-managed state object.
Pitfall 4: profile pollution and deoptimization during measurement
Recall from the profiling and deoptimization chapters that C2 specializes code to the types and branches it has seen. A benchmark can break this in two ways.
- Warmup with different data than the measured run. If warmup only sees
Squareand the timed phase seesCircle, the timed phase includes a deoptimization and a recompilation. That is the pattern inDeoptDemofrom the previous chapters. - Several benchmarks in one JVM. If one benchmark calls a shared helper with a different receiver type, the helper's profile now shows two or three types. Later benchmarks run with a less specialized call site than they would in isolation. The order in which benchmarks run changes the numbers.
To check for the first problem, run with -XX:+PrintCompilation and look for made not entrant lines during the timed phase. If you see them, your timing includes recompilation.
Pitfall 5: loop and OSR artifacts
A benchmark written as one big main with a hot loop is compiled through OSR, not as a normal method entry. OSR code can differ from normal compiled code, because the compiler has less information about values live at the loop entry. The same loop inside a method that is called many times usually gets a standard compilation and may run at a different speed.
If your measurement loop is in main, move the work into a separate method and call that method repeatedly.
Pitfall 6: wall-clock noise from compiler threads
JIT compilation runs on background threads. On a machine with few cores, those threads compete with your application thread, and you see slow rounds that coincide with compilation bursts. Garbage collection, CPU frequency scaling, other processes, and containers with CPU limits add more noise. Report several runs, and use the median or a percentile, not only the minimum or the mean.
A practical measurement procedure
- Put the code under test in its own method. Feed it inputs that the compiler cannot treat as constants.
- Warm up with realistic data until the method is stable. Do not use a fixed count you guessed. Confirm with
-XX:+PrintCompilationthat the method reached tier 4 and that nomade not entrantlines appear afterward. - Measure over many iterations, in several separate JVM launches (forks), and compare them.
- Consume every result.
- Report the spread, not a single number.
In practice, use a harness built for this, such as JMH (the Java Microbenchmark Harness from the OpenJDK project). It handles warmup iterations, forking, black holes, and constant-folding defenses. Writing your own timing loop is fine for rough exploration, as in WarmupTimer, but not for decisions.
Flags that help when investigating
| Flag | Use in benchmarking |
|---|---|
| `-XX:+PrintCompilation` | Confirm tier 4 was reached and check for `made not entrant` during measurement. |
| `-Xint` | Baseline with no compilation. Shows how much the JIT contributes. |
| `-XX:TieredStopAtLevel=1` | C1 only. Quick warmup, lower peak speed. Useful for short-lived tools. |
| `-XX:-TieredCompilation` | C2 only, with interpreter profiling. Slower warmup. |
| `-XX:-BackgroundCompilation` | Makes the thread wait for each compilation. Reduces timing noise from the queue, but changes normal behavior, so use it for diagnosis only. |
| `-Xbatch` | Same effect as turning off background compilation. |
Warmup is also a production concern
Warmup matters outside benchmarks. A freshly started service serves its first requests with interpreted and C1 code. Common consequences:
- Latency is high right after a deploy or a restart, and a load balancer that sends full traffic immediately causes timeouts.
- Autoscaling that adds instances under load can make things worse for a short time, because new instances are slow while they warm up.
- Short-lived JVMs, such as command-line tools, may never reach tier 4 and spend most of their time in the interpreter and C1.
Common mitigations are ramping traffic to new instances gradually, running a synthetic warmup workload before reporting ready, and using -XX:TieredStopAtLevel=1 for tools where startup matters more than peak speed. A warmup workload must exercise the same types and branches as real traffic. Otherwise it teaches the profile the wrong thing, and the first real requests trigger deoptimization.
Summary of the key ideas
- Measure steady state unless you are explicitly measuring startup.
- Use
-XX:+PrintCompilationto check that your measurement sees compiled, stable code. - Defeat dead code elimination and constant folding by consuming results and using non-constant inputs.
- Warm up with the same types and branches as the measured phase.
- Prefer JMH and multiple forks over hand-written timing loops.
Exercise
A benchmark calls Shape.area() through one method. Warmup uses only Square objects, and the timed phase then uses Circle objects. Timed results are slower and noisier than expected, and -XX:+PrintCompilation shows made not entrant lines during the timed phase. What is happening, and how do you fix the benchmark?
Show answer
During warmup the call site saw only Square, so C2 compiled it with the assumption that the receiver is always Square and inlined that case with an uncommon trap for anything else. When Circle appears, the trap fires, the compiled code is made not entrant, execution falls back to the interpreter, and the method is profiled and recompiled. The timed phase therefore includes deoptimization and recompilation. Fix it by warming up with the same mix of types that the timed phase uses, or by deciding deliberately which type mix you want to measure, and by confirming that no made not entrant lines appear after warmup.
Exercise
A loop computes Math.sqrt(i) for many values of i, never uses the result, and reports 0.2 ns per iteration. Give two reasons the number is not trustworthy and one fix for each.
Show answer
First, dead code elimination: the result is unused and Math.sqrt has no side effects, so C2 can remove the computation, and the loop measures almost nothing. Fix it by consuming the result, for example by adding it to a field that is read at the end or by passing it to a harness black hole. Second, the loop probably runs inside main and was compiled through OSR, possibly before reaching steady state, and a literal or constant input may also be folded away. Fix it by moving the work into its own method that is called many times with non-constant inputs, and by using a harness such as JMH with warmup and several forks.