A guide with a dictionary
Mia is a tour guide. Her tour comes as a script written in a special guide language. Every guide in every country can read it, so the same script works for any tour, anywhere.
The tourists don't speak guide language, though. So, sentence by sentence, Mia looks each line up in her dictionary and says it out loud in their language. That works from the first minute, but it's slow: she looks up the same words again every time.
So Mia keeps a little phrasebook. When she notices a sentence she says again and again, she writes its translation into the phrasebook once. Next time she just reads it out, fast.
Looking things up as she goes is how a program starts. Writing the busy parts into the phrasebook while the tour is under way is called JIT compilation, short for "just in time".
Bytecode, the interpreter and the JIT
javac doesn't produce machine code. It compiles Java source to bytecode in .class files: instructions for the
JVM's stack machine, the same on every platform. The JVM then has to get that bytecode running on a real CPU.
HotSpot (the JVM in OpenJDK) does it in two ways:
| Way | How | Trade-off |
|---|---|---|
| Interpreter | Executes bytecode instruction by instruction | Starts instantly, but runs many times slower than compiled code |
| JIT compiler | Compiles a whole method (or loop) to native machine code at run time | Costs CPU time to compile, then runs at full speed |
Compiling everything up front would delay startup and waste effort on code that runs once. So the JVM interprets first and compiles only the code that turns out to be hot. Compilation happens on background compiler threads; the method keeps running in the interpreter until its compiled version is ready, and the compiled code is stored in the code cache, outside the Java heap (see JVM memory).
Tally marks, a pencil draft, then ink
How does Mia know which sentences are worth writing down? She keeps a tally sheet: a mark every time she says a sentence, and a mark every time she goes round the same loop of the tour again.
When a sentence gets enough marks, she writes a quick pencil draft of it into the phrasebook. It's rough, but already much faster than the dictionary. While she uses the draft, she keeps noting details: who asks, and which way the answer usually goes.
If the sentence stays busy, her colleague, a slow and careful writer, uses all those notes to write a polished version in ink. It takes longer to write, but it's the fastest of all.
One more trick: if Mia is halfway through a very long, repeated announcement, she doesn't wait for it to end. She switches to the phrasebook right in the middle and carries on from where she was.
Profiling and tiered compilation
The interpreter profiles as it runs: it counts method invocations and loop back-edges, and when those counters cross thresholds, the method is queued for compilation. HotSpot has two JIT compilers:
- C1 (the client compiler): compiles quickly with light optimisation.
- C2 (the server compiler): compiles slowly, optimises aggressively, using the profile.
Tiered compilation (on by default since JDK 8) uses both, as five levels:
| Level | What runs |
|---|---|
| 0 | Interpreter, with profiling |
| 1 | C1, no profiling (for trivial methods, where C2 couldn't do better) |
| 2 | C1 with invocation and back-edge counters only (used when C2's queue is long) |
| 3 | C1 with full profiling: counters plus branch and receiver-type profiles |
| 4 | C2, fully optimised, no profiling |
The common path is 0 โ 3 โ 4: fast C1 code soon, collecting the detailed profile C2 needs, then C2 code for methods that stay hot.
On-stack replacement (OSR) handles a method that is entered once but loops for a long time, like a main with a
big loop. The back-edge counter triggers a special compilation, and the running frame jumps into compiled code in the
middle of the loop. In -XX:+PrintCompilation output, OSR compilations are marked with %.
How the ink version gets so fast
The careful writer has a few favourite tricks.
- Two sentences that always come together become one smooth sentence, with no pause to turn the page. That's called inlining.
- If Mia only jots a number on a scrap of paper to use within one sentence, the writer notices nobody else ever sees that scrap. So the ink version skips the paper and she keeps the number in her head.
- Instead of "and the next stopโฆ and the next stopโฆ" one at a time, she reads out four stops in one breath.
Key optimisations
C2 works on the whole compiled method at once, so it can do far more than a line-by-line translation:
- Inlining: copies the body of a called method into the caller. It removes call overhead, but more importantly it
lets every other optimisation see across the call. Small methods are inlined at any call site that has run, hot or not (by default
up to 35 bytes of bytecode,
-XX:MaxInlineSize); at hot call sites, methods up to 325 bytes are (-XX:FreqInlineSize). This is why small getters and helper methods cost nothing in hot code. - Escape analysis: works out whether an object can be seen outside the compiled code. If it can't
escape, C2 can apply scalar replacement (keep its fields in registers and skip the heap allocation
entirely, so there is less work for the garbage collector) and lock
elision (drop
synchronizedon an object no other thread can see). It depends on inlining: an object passed to a method that wasn't inlined counts as escaping. - Loop optimisations: loop unrolling (several iterations per pass, fewer branches), range-check elimination (array bounds checked once outside the loop, not on every access), and hoisting invariant code out of the loop.
Others include constant folding, dead-code elimination and intrinsics: hand-written machine code for methods such as
System.arraycopy or Math operations.
When a guess goes wrong
The careful writer is clever, and a little daring. The tally sheet says: whenever tourists ask "which way to the museum?", they've always meant the art museum. So the ink version says "the art museum is straight ahead" and doesn't even mention the other museum. That makes it short and fast.
Then one day a tourist asks about the science museum. The ink sentence doesn't fit. Mia doesn't make something up: she crosses the sentence out, goes back to her dictionary for that question, and answers properly. Going back like that is called deoptimisation.
The tally sheet now shows both museums, so later the writer makes a new ink version that handles both.
Speculation and deoptimisation
C2 optimises for what the profile says has happened, not for everything that could:
- A call site that has only ever seen one receiver type (monomorphic; for example, a
shape.area()call that has only ever seenCircle) is inlined behind a cheap type check; two types (bimorphic) get two inlined paths. With more (megamorphic), it stays a virtual call, unless one type makes up at least 90% of calls (-XX:TypeProfileMajorReceiverPercent), which is then inlined with a virtual-call fallback. - Branches the profile never saw taken are left out of the compiled code.
- Class hierarchy analysis: if only one loaded class implements a method, calls to it are treated as direct.
Each guess is protected by a guard. When a guard fails (a new type arrives, a never-taken branch is taken, a new
subclass is loaded), the compiled code hits an uncommon trap and deoptimises: the JVM rebuilds the
interpreter's frame from the compiled frame and carries on in the interpreter, with the same results. The compiled
method is marked made not entrant (visible in -XX:+PrintCompilation), so new calls don't use it. The method is
profiled again and recompiled with the wider picture.
This is why the JIT can beat a static compiler in steady state, and also why performance can dip briefly when traffic changes shape. If the same guess keeps failing, HotSpot eventually stops making it for that method.
Slow first tour, and a phrasebook with few pages
Mia's first tour of the day is always the slowest: the phrasebook is still empty, so she looks everything up. By the afternoon, the busy sentences are all in ink and the tour flies. That getting-up-to-speed is called warm-up.
So if you want to time how fast a guide is, timing her first tour is unfair. A fair stopwatch lets her do a few practice tours first, only then starts timing, and repeats it on fresh days so one lucky day doesn't fool you.
And the phrasebook only has so many pages. If it fills up, Mia can't write anything new, and every new sentence stays slow.
Warm-up, benchmarks and the code cache
A freshly started JVM is slow: code is interpreted, then C1-compiled, and only reaches C2 speed after enough calls. That warm-up shows up as slow first requests after a deploy, which is why services often send warm-up traffic before taking real load.
It also makes naive benchmarks wrong. A loop timed with System.nanoTime() mixes interpreted and compiled runs, and
C2 may remove the work entirely if the result is unused (dead-code elimination). Use JMH, the OpenJDK benchmark
harness. It runs warm-up iterations that aren't measured, forks fresh JVMs so profiles from one benchmark don't skew
another, and gives you a Blackhole so results aren't optimised away:
1@State(Scope.Thread)2@Warmup(iterations = 5)3@Measurement(iterations = 5)4@Fork(2)5public class PriceBenchmark {6double[] prices = new double[1_000];78@Benchmark9public void total(Blackhole bh) {10double sum = 0;11for (double p : prices) sum += p * 1.2;12bh.consume(sum); // keeps C2 from deleting the loop13}14}
Compiled code lives in the code cache, a fixed-size native memory area. Since JDK 9 it is segmented (non-method,
profiled and non-profiled code). With tiered compilation, its default maximum size (-XX:ReservedCodeCacheSize) is
240 MB. If a segment fills, the JVM logs a warning such as CodeHeap 'non-profiled nmethods' is full. Compiler has been disabled. and stops compiling. Compilation resumes only if old, cold code is flushed, so in the meantime newly
hot code stays interpreted. Check usage with jcmd <pid> Compiler.codecache and raise the size if needed.
To watch the JIT, run with -XX:+PrintCompilation, or record with JDK Flight Recorder, which captures compilation
and deoptimisation events.
Other ways to start fast
Waiting for the phrasebook to fill isn't the only option.
- A different careful writer. Some guides hire another writer with the same job, whose ink versions are sometimes better, sometimes not.
- A full translation printed before the trip. The night before, someone translates the whole script, ahead of time, and prints it. Mia is fast from the very first sentence. But the printed book can't change during the tour, so everything the tour might need has to be known in advance.
- Yesterday's notes. Mia keeps yesterday's tally sheet and her dictionary bookmarked at the right pages, so this morning she starts with a head start.
- A snapshot of a warmed-up guide. Take a photo of Mia at full speed, phrasebook filled in, and next time start the tour from that exact moment.
Alternatives: Graal, native images, AOT cache and CRaC
- Graal JIT: an optimising compiler written in Java that plugs into HotSpot through the JVM Compiler Interface
(JVMCI) in place of C2. It was experimental in OpenJDK 10 to 16 (JEP 317) and removed from OpenJDK in JDK 17
(JEP 410, which also removed the experimental
jaotcAOT compiler). It ships with GraalVM distributions, though since September 2025 Oracle steers its own customers back to C2. - GraalVM Native Image (
native-image): ahead-of-time compiles the application and the parts of the JDK it uses into a standalone executable. It starts in milliseconds and uses less memory, with no warm-up, but it assumes a closed world: everything reachable must be known at build time, so reflection, dynamic proxies and resources need metadata. Spring Boot 3's AOT processing generates that for Spring apps, and in exchange bean definitions are fixed at build time (for example,@Profilecan't switch beans at run time). With no runtime profile, peak throughput can be lower than a warmed-up JIT. - CDS and the AOT cache (Project Leyden): Class Data Sharing archives parsed class metadata so it isn't rebuilt on
every start. JDK 24 extended it into the AOT cache (JEP 483): a training run records the classes the app loads
and links, and later runs start with them ready. JDK 25 added a one-step
-XX:AOTCacheOutput(JEP 514) and stores method profiles in the cache (JEP 515), so the JIT can compile hot methods sooner. It holds classes and profiles, not machine code (caching compiled code is still a draft JEP in Project Leyden): the JIT still compiles at run time, and you keep full Java dynamism. - CRaC (Coordinated Restore at Checkpoint): checkpoints a running, warmed-up JVM to disk and later restores it, JIT-compiled code included. It needs a CRaC-enabled JDK (such as Azul Zulu builds with CRaC), runs on Linux only, and the checkpoint files hold memory contents, secrets included, so protect them. Spring Boot supports it from 3.2.
With Spring Boot (Java 25+), extract the jar first, then do a training run that starts the context and exits:
1java -Djarmode=tools -jar app.jar extract --destination application2cd application3# training run: start the app, refresh the context, exit, write the cache4java -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh -jar app.jar5# every later start (same JDK, same extracted app)6java -XX:AOTCache=app.aot -jar app.jar
A native image is built with GraalVM's build tools (mvn -Pnative native:compile), and a CRaC checkpoint with
-XX:CRaCCheckpointTo=<dir> plus jcmd <pid> JDK.checkpoint, restored with -XX:CRaCRestoreFrom=<dir>.
| Option | Startup | Peak speed | Catch |
|---|---|---|---|
| Plain JIT | Slow, then warms up | Best, from real profiles | Warm-up time |
| AOT cache | Faster | Same as JIT | Needs a training run on the same JDK |
| CRaC | Near-instant, already warm | Same as JIT | Linux only, special JDK, checkpoint holds secrets |
| Native Image | Near-instant | Often lower | Closed world, long builds |