JIT Compilation
How HotSpot turns bytecode into fast machine code — tiered compilation (C1/C2), profiling, inlining, escape analysis, devirtualisation, loop optimisations, deoptimisation, warm-up, and benchmarking with JMH.
A just-in-time (JIT) compiler compiles code to machine instructions while the program runs. That sounds like a handicap compared to compiling ahead of time — but it has a huge advantage: the JIT can see how the program actually behaves (which types appear, which branches are taken) and optimise for that. Hot Java code often runs as fast as C++.
Tiered compilation
HotSpot executes each method at one of five tiers, moving up as it gets hotter:
| Tier | Executed by | Purpose |
|---|---|---|
| 0 | Interpreter | Start immediately, collect basic counts |
| 1 | C1, no profiling | Trivial methods (getters) that won't benefit from more |
| 2 | C1, limited profiling | Used when C2's queue is busy |
| 3 | C1, full profiling | Fast native code that records types and branches |
| 4 | C2 | Aggressive optimisation using the profile |
The typical path is 0 → 3 → 4. Thresholds are counts of invocations and loop back-edges (around 10,000 for C2). Long-running loops in a method that's only called once can be compiled mid-execution via on-stack replacement (OSR).
This is warm-up: the same request is slow for the first few thousand executions, then fast.
Profile-guided optimisations
Inlining — the mother of all optimisations
Replacing a call with the body of the called method removes call overhead and, more importantly, exposes the combined code to further optimisation (constant folding, dead-code elimination, escape analysis). C2 inlines small methods (under ~35 bytes of bytecode) and hot methods up to ~325 bytes, to a limited depth. Getters, setters and small helpers effectively cost nothing.
Devirtualisation
A virtual call (shape.area()) normally means a vtable lookup and blocks inlining. But the profile might show that a call site has only ever seen one type:
| Call site profile | Optimisation |
|---|---|
| Monomorphic (1 type seen) | Guard "is it a Circle?" then the inlined Circle.area() body |
| Bimorphic (2 types) | Two guarded inlined paths |
| Megamorphic (3+ types) | Real virtual call through the vtable; no inlining |
Class hierarchy analysis (CHA) can do better still: if only one class implementing an interface is loaded, calls need no guard at all — until a second implementation is loaded, which triggers deoptimisation.
Escape analysis
If an object never escapes the method (not stored in a field, not returned, not passed to un-inlined code), the JIT can:
- Scalar replacement: not allocate it at all, keeping its fields in registers.
- Lock elision: remove synchronisation on it (no other thread can see it).
double distance(double x1, double y1, double x2, double y2) {
Point a = new Point(x1, y1); // never escapes...
Point b = new Point(x2, y2);
return a.distanceTo(b); // ...after inlining, no Point objects are allocated
}Other optimisations
- Constant folding and propagation, dead-code elimination, common subexpression elimination.
- Branch pruning: code that profiling shows is never taken is replaced by an "uncommon trap" that deoptimises if it ever happens.
- Loop optimisations: unrolling, loop-invariant hoisting, range-check elimination (proving array indices are in bounds so per-access checks disappear).
- Auto-vectorisation (SIMD): simple loops over arrays use vector instructions (and the Vector API gives explicit control).
- Intrinsics: methods like
System.arraycopy,Math.sqrt,String.equals,Integer.bitCountand CRC32 are replaced by hand-written CPU-specific assembly. - Null-check elimination: implicit null checks via hardware traps instead of explicit comparisons.
Deoptimisation
Optimistic optimisations are bets. When an assumption is violated — a new subclass appears, an "impossible" branch executes, a class is redefined — the JVM deoptimises: it discards the compiled code, reconstructs interpreter frames from the compiled state, continues in the interpreter, and may recompile later with the new profile. This is what makes aggressive speculation safe.
Seeing what the JIT does
java -XX:+PrintCompilation -jar app.jar
# timestamp id tier method size
# 312 45 3 java.lang.String::hashCode (49 bytes)
# 488 97 4 com.acme.Pricing::total (88 bytes)
# 902 97 4 com.acme.Pricing::total (88 bytes) made not entrant <- deoptimised
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining ... # inlining decisions
# JITWatch visualises compilation logs; -XX:+PrintAssembly (with hsdis) shows generated machine codeBenchmarking correctly: JMH
Naive timing loops lie: they measure the interpreter (no warm-up), or the JIT eliminates the code because the result is unused (dead-code elimination), or constant-folds inputs.
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5) @Measurement(iterations = 5) @Fork(2)
@State(Scope.Thread)
public class ConcatBench {
String a = "hello", b = "world"; // fields, not constants: prevents constant folding
@Benchmark
public String plus() { return a + b; } // return the result: prevents DCE
@Benchmark
public void builder(Blackhole bh) {
bh.consume(new StringBuilder(a).append(b).toString());
}
}JMH (the Java Microbenchmark Harness, from the OpenJDK team) handles warm-up, forking fresh JVMs, dead-code prevention and statistics.
JIT vs AOT
| JIT (HotSpot C2, Graal JIT) | AOT (GraalVM native-image) | |
|---|---|---|
| Start-up | Slow (interpreter, class loading, warm-up) | Milliseconds |
| Memory | Higher (compiler, profiles, metadata) | Lower |
| Peak performance | Highest (profile-guided speculation) | Somewhat lower (PGO helps) |
| Dynamic features | Full reflection, dynamic class loading | Need configuration at build time |
| Good for | Long-running servers | CLIs, serverless, scale-to-zero containers |
Middle grounds: CDS/AOT caches and Project Leyden (Java 24+) save class loading and profiling work from a training run to speed up start-up while keeping the JIT; CRaC checkpoints a warmed-up JVM and restores it.
- HotSpot interprets first, then compiles hot methods with C1 (profiling) and C2 (optimised).
- Inlining enables most other optimisations; monomorphic call sites inline, megamorphic ones don't.
- Escape analysis removes allocations and locks for objects that don't escape.
- Speculative optimisations are protected by deoptimisation.
- Warm-up matters; benchmark with JMH, never with naive loops.
- AOT (native-image) trades peak performance and dynamism for instant start-up.
QWhy can Java be as fast as C++ despite running on a VM?hard
The JIT compiles hot code to native machine code using runtime profiles that an ahead-of-time compiler doesn't have: it inlines across virtual calls that are monomorphic in practice, removes allocations via escape analysis, eliminates bounds and null checks, prunes branches never taken and vectorises loops. Deoptimisation lets it speculate safely. The costs are warm-up time, memory for the compiler, and GC overhead.