Sub topic 14
JIT Compilation and Warmup
This chapter assumes you can run Java from the command line, read a CPU profile, and know that the JVM runs your bytecode with both an interpreter and a compiler. It explains why the same code runs at different speeds over time. It also explains how that distorts profiles and benchmarks.
Why the first seconds are slow
The JVM does not compile your program ahead of time. It starts by interpreting bytecode, which is simple and slow. While interpreting, it counts how often each method is called and how often each loop jumps backward. When a counter crosses a threshold, the method is queued for the just-in-time (JIT) compiler. The compiler turns it into machine code, and later calls use that code.
This has three consequences for profiling:
- Early requests are slower than later ones, because their code is still interpreted or only lightly optimized.
- Compiler threads use CPU while they work, so a profile taken at startup contains JIT work that disappears later.
- The machine code can change while the program runs. A profile from minute one may not describe minute ten.
Tiered compilation
HotSpot, the standard JVM, has two compilers and uses both. C1 compiles quickly and produces moderately fast code. C2 compiles slowly and produces highly optimized code. Tiered compilation, on by default, moves a method through numbered levels.
| Level | Executed by | Notes |
|---|---|---|
| 0 | Interpreter | Counts invocations and loops |
| 1 | C1, no profiling | Used for trivial methods that C2 could not improve |
| 2 | C1, limited profiling | Used when the C2 queue is long |
| 3 | C1, full profiling | The usual first compiled tier |
| 4 | C2 | Fully optimized, using profile data from level 3 |
The profile gathered at level 3 is what lets C2 make good guesses. For example, it records which classes actually appear at a virtual call site, and which branch is almost never taken.
On-stack replacement
A method called once that contains a long loop would never reach the invocation threshold. The loop's backward-jump counter catches this case. The JVM compiles the method and switches to the compiled version in the middle of the running loop. This is on-stack replacement (OSR). It is why a main method with a hot loop still gets optimized. In -XX:+PrintCompilation output, OSR compilations are marked with a %.
Speculation and deoptimization
C2 optimizes for what it has seen. If a call site only ever saw one class, C2 inlines that method behind a cheap type check. If a branch was never taken, C2 may leave it out entirely. When a guess turns out wrong, the JVM discards the machine code and returns to the interpreter. This is deoptimization. The method then goes through the tiers again.
Deoptimization is normal and usually brief. It becomes a problem when it repeats. A common cause is a workload that changes phase, such as a service that is idle all night and then receives a different mix of requests in the morning. Another cause is a class loaded later that adds a second implementation to a call site that was monomorphic (one type only).
Watching the JIT work
This program times the same work 15 times. It prints a checksum at the end so the compiler cannot discard the result.
public class Warmup {
static long work(int n) {
long sum = 0;
for (int i = 0; i < n; i++) {
sum += Integer.toString(i).length();
}
return sum;
}
public static void main(String[] args) {
long sink = 0;
for (int round = 1; round <= 15; round++) {
long start = System.nanoTime();
sink += work(200_000);
long micros = (System.nanoTime() - start) / 1_000;
System.out.println("round " + round + ": " + micros + " us");
}
System.out.println("sink=" + sink);
}
}Run it twice, once with compilation logging and once with the JIT off:
java -XX:+PrintCompilation Warmup.java
java -Xint Warmup.javaIn the first run, the early rounds are usually several times slower than the later ones, and lines for Warmup::work appear as it moves through the tiers. Each line shows a timestamp in milliseconds, a compile ID, the tier number, and the method. The word made not entrant means the code was invalidated, often because it was replaced by a better tier or because of deoptimization. With -Xint, every round is slow and the times stay flat. Exact numbers depend on your machine, so compare the shape of the output, not the values.
Flags for investigation
| Flag | Effect | Use |
|---|---|---|
| `-XX:+PrintCompilation` | Logs each compilation | See what is compiled and when |
| `-Xint` | Interpreter only | Measure the no-JIT baseline |
| `-XX:TieredStopAtLevel=1` | C1 only | Fast startup, lower peak speed |
| `-XX:-TieredCompilation` | C2 only, with interpreter profiling | Rarely better, mainly for experiments |
| `-XX:CICompilerCount=N` | Number of compiler threads | Tune on small containers |
Treat these as diagnostic tools. Changing them in production without measurement often makes things worse.
JIT in Java Flight Recorder
The profile settings from the JFR chapter record compilation events such as jdk.Compilation, and jdk.Deoptimization on recent JDKs. In JDK Mission Control you can see which methods took long to compile and whether the same method is deoptimized many times. For the code cache, a fixed-size memory region that holds machine code, you can use jcmd:
jcmd <pid> Compiler.codecacheIf the code cache fills up, the JVM stops compiling new methods and logs a warning. Throughput then drops sharply and does not recover. This is rare, but the symptom is easy to misread as a code regression.
Effects on profiling and measurement
Warmup changes how you should collect data:
- Do not profile only the first minute of a service, unless startup is the problem you want to fix. Start the recording after the load has run for a while.
- When a hot method in the profile is named
Interpreteror a C1 frame, the process may not have warmed up yet. Look at a later window of the recording. - A timing taken in a single run of
mainmeasures a mix of interpreter, C1 and C2 speeds. This is the main reason hand-written timing loops mislead, and it is why JMH exists. - Compare before and after in the same state. Both runs should be warmed up, or both should be cold.
Reducing warmup cost
When warmup itself is the problem, for example in short-lived command-line tools or autoscaled services, you have several options:
- Use
-XX:TieredStopAtLevel=1to give up peak speed for quicker early performance and lower compiler CPU use. - Run a synthetic warmup before the instance takes traffic, such as replaying representative requests during startup, and only then report it ready to the load balancer.
- Use Class Data Sharing archives to cut class loading time. This helps startup but does not remove JIT warmup.
- Consider newer features such as CRaC or GraalVM native image. They change the trade-offs, since a native image loses the runtime profile that C2 uses.
A warmup that is too small can cause more harm than none. If it exercises only one code path, C2 may optimize for that path and then deoptimize when real traffic differs.
Common mistakes
- Reading a startup profile as if it described steady state.
- Timing code once with
System.nanoTime()and trusting the result. - Benchmarking with a loop whose result is unused, which lets C2 remove the work.
- Benchmarking with one input type, then deploying code that sees many types.
- Disabling tiered compilation because a blog post suggested it, without measuring.
Exercise
A service shows high CPU and slow responses for the first two minutes after every deployment, then settles. A JFR recording from the first minute shows many frames in compiler threads and in interpreted code. Name two ways to confirm that warmup is the cause, and one way to reduce its impact.
Show answer
To confirm, (1) record a second JFR window after the service has run under load for several minutes and check that compiler-thread CPU and interpreted frames mostly disappear, and (2) run with -XX:+PrintCompilation or look at jdk.Compilation events to see compilations continuing during the slow period and stopping afterwards. To reduce the impact, replay representative requests before reporting the instance as ready, so the hot methods reach C2 before real users arrive. Lowering the tier with -XX:TieredStopAtLevel=1 is an alternative if lower peak speed is acceptable.