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.

Advanced 5 min readLesson 11 of 14 Interview Q&A

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:

TierExecuted byPurpose
0InterpreterStart immediately, collect basic counts
1C1, no profilingTrivial methods (getters) that won't benefit from more
2C1, limited profilingUsed when C2's queue is busy
3C1, full profilingFast native code that records types and branches
4C2Aggressive 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).

interpretedC1 + profilingC2 optimised03716

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 profileOptimisation
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).
Java
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.bitCount and 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

Shell
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 code

Benchmarking 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.

Java
@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-upSlow (interpreter, class loading, warm-up)Milliseconds
MemoryHigher (compiler, profiles, metadata)Lower
Peak performanceHighest (profile-guided speculation)Somewhat lower (PGO helps)
Dynamic featuresFull reflection, dynamic class loadingNeed configuration at build time
Good forLong-running serversCLIs, 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.

Key takeaways
  • 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.
Interview questions
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.