TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท java ยท jvm ยท performance ยท compilers

JIT compilation

How the JVM turns bytecode into fast machine code while your program runs. It interprets first, profiles which methods and loops are hot, compiles them in tiers with optimisations based on what it has seen, and falls back to the interpreter when a guess turns out wrong.

15 min6 animations

๐Ÿ“š Builds on๐Ÿ› ๏ธ JVM memory: heap, stack and metaspace

๐Ÿ–จ๏ธ Cheat sheet

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:

WayHowTrade-off
InterpreterExecutes bytecode instruction by instructionStarts instantly, but runs many times slower than compiled code
JIT compilerCompiles a whole method (or loop) to native machine code at run timeCosts 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).

From bytecode to machine code4 steps
Tour script0123โœ๏ธScript writer๐Ÿง‘โ€๐Ÿ’ผGuide with dictionary๐ŸงณTourists
Press play and watch it happen!

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:

LevelWhat runs
0Interpreter, with profiling
1C1, no profiling (for trivial methods, where C2 couldn't do better)
2C1 with invocation and back-edge counters only (used when C2's queue is long)
3C1 with full profiling: counters plus branch and receiver-type profiles
4C2, 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 %.

Counting, then compiling in tiers4 steps
Tally sheet01234๐Ÿง‘โ€๐Ÿ’ผGuide with dictionaryโœ๏ธQuick pencil writer๐Ÿ–‹๏ธCareful writer
Press play and watch it happen!

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 synchronized on 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.

What the optimising compiler does4 steps
Ink version0123๐Ÿ’ถ Price sentence๐Ÿงพ Tax sentence๐Ÿ–‹๏ธCareful writer๐Ÿ“„ Scrap of paper
Press play and watch it happen!

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 seen Circle) 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.

Speculate, then deoptimise4 steps
๐ŸงณTourist๐Ÿ“’ Ink version๐Ÿง‘โ€๐Ÿ’ผGuide with dictionary๐Ÿ–‹๏ธCareful writer
Press play and watch it happen!

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 {6    double[] prices = new double[1_000];7 8    @Benchmark9    public void total(Blackhole bh) {10        double sum = 0;11        for (double p : prices) sum += p * 1.2;12        bh.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.

Warm-up, benchmarks and the code cache4 steps
Tour times01234Phrasebook pages0123๐Ÿง‘โ€๐Ÿ’ผGuideโฑ๏ธFair stopwatch
Press play and watch it happen!

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 jaotc AOT 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, @Profile can'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>.

OptionStartupPeak speedCatch
Plain JITSlow, then warms upBest, from real profilesWarm-up time
AOT cacheFasterSame as JITNeeds a training run on the same JDK
CRaCNear-instant, already warmSame as JITLinux only, special JDK, checkpoint holds secrets
Native ImageNear-instantOften lowerClosed world, long builds
Other ways to start fast4 steps
๐Ÿ–‹๏ธAnother careful writer๐Ÿ“• Printed translation๐Ÿ—’๏ธ Yesterday's notes๐Ÿ“ธ Snapshot photo๐ŸšŒToday's tour
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about JIT compilation, told the same way as the story.
  1. Why doesn't the guide write every sentence of the script into her phrasebook before the tour starts?
  2. A tourist asks about the science museum, but the ink version assumed everyone means the art museum. What does the guide do?
  3. You time a guide on her very first tour of the morning and decide she's slow. What's wrong with that?
  4. The guide's phrasebook has run out of pages. What happens next?
  5. Which way of starting fast can't change anything during the tour, because everything had to be known the night before?
Answer every question to check.Passing marks JIT compilation as done.
Got the hang of JIT compilation? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โš™๏ธ Java under the hoodStep 5 of 5

โ† Previous on the path๐Ÿ› ๏ธ JVM memory: heap, stack and metaspaceLast step ๐ŸŽ‰Back to the path