Lesson · JVM Internals
Execution engine and JIT: where the speed comes from
18 min readExecution Engine & JIT
The interpreter starts executing immediately and measures while it works. Hot methods climb to C1, then to C2, which compiles aggressively because a profile says it can. Inlining, speculation, deoptimization, and the reason a benchmark without warm-up measures the wrong thing.
The benchmark that lied
Two timings of the same method, a moment apart:
long t0 = System.nanoTime(); sum(data); // the first call: nobody has compiled anything yet long cold = System.nanoTime() - t0; for (int i = 0; i < 30_000; i++) { sum(data); // warm-up: the JIT is not idle during this loop } long t1 = System.nanoTime(); sum(data); long warm = System.nanoTime() - t1; // not a benchmark either; JMH exists for that
- The cold number is a measurement of the interpreter, plus class loading, plus a JIT that has not decided this method matters. It is a real number about a real phase, and the phase is warm-up.
- The warm number is a measurement of compiled code, shaped by guesses the compiler made from the profile of the loop above. Also real, also not a property of the method.
- The gap between them is the topic of this lesson: who decided to compile, what the compiled code assumed, and what happens when an assumption stops holding.
Cold is not slow code; cold is code that has not met the compiler yet. Interpretation is stage one of a plan, not a fallback, and almost every Java performance misunderstanding starts by forgetting which stage a number came from.
Three engines, one method
HotSpot runs bytecode three ways. The interpreter executes directly and counts. C1 compiles quickly, with modest optimizations, and keeps watching. C2 compiles slowly and aggressively, speculating from what C1 observed. Tiered compilation, the default since Java 8, moves a hot method through all of them.
| Stage | Speed of compilation | What it gives you |
|---|---|---|
| Interpreter (level 0) | none | immediate start and full counting: invocations, loop back-edges, branch outcomes, receiver types |
| C1 (levels 1 to 3) | fast | a big step up within the first moments, plus the profile C2 needs; the levels differ in how much profiling is collected |
| C2 (level 4) | slow | the aggressive set: inlining, devirtualization, escape analysis, loop transformations, guarded by checks |
- A hot method typically passes through C1 before C2. The exact transitions and the thresholds that trigger them are VM, version and flag dependent; quote the shape, never the numbers.
- Why not C2 from the start? Compiling everything with the slow compiler would burn CPU on methods that run once and delay the ones that matter. Compiling nothing would leave an interpreter forever. The ladder is the compromise.
- Compilation is asynchronous. The request goes to compiler threads while execution continues; nobody waits for the optimizer.
Interpretation is not a fallback; it is stage one. The JVM starts the program before it knows anything about it, then spends that running knowledge on the methods worth compiling.
Tiered compilation · the ladder and the way back
thresholds are VM and version dependent: the shape is the lesson
OSR: on-stack replacement
A loop already executing cannot wait for a next call. The VM compiles a version the running frame can enter at the loop back-edge and swaps the interpreter frame for the compiled one, mid-loop.
Deopt: uncommon trap
An assumption fails (a new receiver type, an altered hierarchy). The compiled frame carries frame state, enough to rebuild the interpreter frames, and execution continues at the same bytecode position. The method is re-profiled, then recompiled with the new fact.
What the compiled code bets on
Watch it happen: -XX:+PrintCompilation prints one line per compile, where a percent sign marks an OSR compile and made-not-entrant marks deoptimized code. Adding -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining shows which call sites were inlined and which were refused.
Hot means counted
Hotness is not guessed from the source. Method entry increments an invocation counter, and each jump back in a loop increments a back-edge counter; when a counter crosses its threshold, the method is queued for compilation. A method that is called once stays interpreted forever, however complicated it looks.
Long loops expose the awkward case: a method can cross the threshold while it is already executing. Compiling it would only help the next call, and a loop that runs for minutes never has a next call. That is what on-stack replacement exists for.
- Two counters, two shapes: many short calls grow the invocation counter; one very long loop grows the back-edge counter instead.
- OSR compiles for the loop, not for the method: the VM compiles a version the running frame can jump into at the loop back-edge and swaps the interpreter frame for the compiled one, mid-loop.
- Profiles are a byproduct. While counting, the runtime also records which receiver types and branch outcomes it sees, because that is the evidence C2 will speculate on.
Counters decide, not the source. The same method can be cold in one program and compiled to its final tier in another. Whether a loop is slow is answered by a profile, never by reading the code.
Inlining: the optimization that unlocks the rest
Inlining replaces a call with the body of the callee. On its own that saves one call; the real value is what it removes, which is the wall between two methods. Once the body is inside the caller, constants flow into it, branches on those constants disappear, and optimizations that need to see the whole object lifetime suddenly can.
What gets inlined is decided by size and by the profile. Tiny methods are inlined almost anywhere; larger ones only at call sites the profile likes, controlled by VM budgets with flags such as MaxInlineSize and FreqInlineSize. A call site with one receiver type is the favourite candidate.
- Monomorphic: one receiver type at the site. The JIT inlines the target directly and then constant-folds through the inlined body.
- Bimorphic: two types seen. Both can still be inlined, behind a cheap type check that picks the right body.
- Megamorphic: many types seen. The profile gives up, the call stays virtual, and the surrounding code usually cannot be optimized across it. Adding one more implementation to a hot call site can cost far more than the implementation itself.
The JIT bets on your monomorphic call sites; a second implementation makes it fold. Shaping hot paths around one dominant implementation (an interface with one real implementor, final classes, a sealed hierarchy) is JIT friendliness, not just style.
Speculation: optimizing for the observed past
C2 compiles for what the profile showed and guards the assumption with a cheap check. The result is fast and provisional: fast because the assumption removed work, provisional because the guard can fail and the runtime has a way to retreat (deoptimization, next section).
- Class hierarchy analysis: if only one implementation of a method exists, calls to it can be devirtualized. Loading a second implementation makes that inference false, and the first execution at the old site notices.
- Escape analysis: if an object provably never leaves its method, the compiler may dissolve it into registers (scalar replacement) or remove the locking around it. This is exactly the layer 3 behaviour from memory-model-basics: an optimization nothing observable can detect.
- Loop transformations: unrolling, invariant hoisting and range check elimination follow from the same evidence, and they are usually the reason a numeric loop hits native speed.
- Everything is profile-shaped. A branch that always went one way is compiled as if it always will, and a call site that always saw one receiver type is compiled as if it always will. Change the data, and the compiled version changes too, sometimes by starting over.
Speculation is a bet with a refund. The JVM never has to be right about your future data; it only has to be able to notice when it was wrong and step back. That safety net is what makes the aggressive optimizations legal at all.
Deoptimization: the bet is called off
When an assumption breaks, the compiled version of a method stops being valid. The failing points are called uncommon traps: places where the compiled code says this should never happen, and it happened. The most common cause is a call site that was inlined for one receiver type, until a second one arrived.
The compiled frame carries enough recorded state to rebuild what the interpreter needs: locals, operand stack, position. The runtime reconstructs those frames and continues, interpreted, at the same bytecode position. No exception is thrown and no wrong answer is produced; the engine just changed. Afterwards the method is re-profiled with the new fact and can be recompiled around it.
- What triggers it: a type profile invalidated by a new implementation at a call site, a class hierarchy change that invalidates compiled assumptions, a guard whose recorded behaviour no longer holds. Anything the compiled code assumed.
- What it costs: a stretch of interpreted execution, plus the recompilation. Repeated deoptimization of the same method (a deopt loop, often caused by profiles that keep changing) is slower than never having been optimized at all.
- How to see it: deoptimized code turns up in -XX:+PrintCompilation output as made not entrant, and diagnostic flags print the reason in detail.
Deoptimization is the mechanism that lets the JVM be aggressive. The compiled code is allowed to assume, because there is a legal, precise way to take the assumption back: rebuild the interpreter frames and carry on.
One method · sum in a hot loop
This step
immediate start, full counting, modest speed
Call 1: the loop method runs interpreted. The entry counter ticks, the interpreter records the receiver type it sees, and the per-operation cost is the interpreter's.
Why benchmarks must warm up
A long-running service spends almost all its life in C2 code; a benchmark that runs a method once measures the interpreter and the warm-up. Neither number is wrong, but only one of them describes the thing people usually mean by performance, and mixing them is how two teams disagree about the same method.
There are three practical reasons for warm-up, and a fourth for using a real harness: the code starts interpreted, C2 needs enough executions to have something worth speculating about, the compiler threads need wall-clock time to finish the work, and a hand-rolled loop has about five ways to measure nothing at all.
# one line per compilation: id, tier, method, size; a percent sign marks an OSR compile java -XX:+PrintCompilation -jar service.jar # which call sites were inlined, printed as the compile happens java -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining -XX:+PrintCompilation -jar service.jar
- Dead code elimination: a result nobody uses lets the JIT delete the computation, so the loop you timed may not have run.
- Constant folding: a loop with the same input every iteration can collapse into one multiplication.
- No warm-up: a single cold measurement describes interpretation, not the code.
- JMH exists for this: it forks a fresh JVM, warms up by policy, keeps the computation alive with Blackholes, runs several measurement iterations, and reports error bars.
- Watch the compiler while you do it: -XX:+PrintCompilation prints one line per compile (id, tier, method, bytecode size); adding -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining shows which calls were inlined, in the caller, and which were not.
Warm-up is not a trick: it is the compiler arriving. A benchmark that models a long-running service must include warm-up; a benchmark about cold start must measure the first run and say so. Without that sentence attached, a Java timing number is unreadable.
The performance-question playbook
Five moves when someone says a Java method got slower:
- Ask which engine produced the number: interpreter, C1, C2, or a deopt region. A phase-free claim about Java speed is incomplete.
- Ask for evidence, not theory: PrintCompilation lines, a profiler trace, inlining reports. Guessing which optimization ran is how benchmark arguments last all afternoon.
- For a hot path, count the implementations at its call sites. One is inlinable, two are still workable, many mean the optimizer has already given up.
- Distrust micro-benchmarks without a harness that warms up, blackholes results and repeats: the nanoTime loop pattern is where wrong numbers are born.
- Remember that every optimization is a statement about the data the program actually produced. Change the data, and the compiled version changes with it, sometimes by starting over.
Speed in Java is a timeline, not a property. Interpreter, C1, C2 and the occasional step back to the interpreter are phases of the same method. The useful question is which phase a workload lives in, and what would move it.
The first measurement is almost never the number you want
Cold code is interpreted code, so a one-shot timing measures class loading, interpretation, and a JIT that has not yet decided the method is worth compiling. Measure after warm-up for steady state, measure before it for cold start, and never attribute either number to the algorithm. That is the entire reason JMH exists.
Interview angles
Walk through what happens to a method from its first call to peak performance.+
It runs interpreted while counters and profiles accumulate. When the invocation or back-edge counter crosses a threshold it is queued for C1, which compiles quickly and keeps profiling. Enough evidence promotes it to C2, which compiles aggressively around guarded assumptions. A long loop can jump the queue through on-stack replacement.
What is tiered compilation?+
The default policy that combines the interpreter, C1 and C2 in levels, so methods get compiled cheaply and quickly first and expensively later only if they stay hot. C1 buys warm-up speed and collects the profile; C2 buys peak speed and speculates on that profile.
Level 0 is the interpreter, levels 1 to 3 are C1 with different amounts of profiling, level 4 is C2. Real transitions and thresholds are VM and version dependent, so the interview-safe answer describes the structure, not the numbers.
Common misconception: That Java methods are either interpreted or compiled. At any moment different methods are in different tiers, and the same method can move between tiers in both directions.
What is on-stack replacement?+
Compiling a method for a loop that is already running and swapping the interpreter frame for the compiled one at the loop back-edge. Without OSR, a method containing one very long loop would never benefit from compilation, because it never returns to be called again.
Follow-up: Why does the back-edge counter, not the invocation counter, usually trigger this case?
Why is inlining considered the most important optimization?+
It removes the boundary between caller and callee, which is what lets every other optimization see further: constants propagate, branches fold away, escape analysis works on the whole lifetime. The JIT only inlines what the profile suggests, so monomorphic call sites are the ones that get fast.
Size budgets (MaxInlineSize, FreqInlineSize) limit how much code is copied into a caller, and megamorphic call sites are left as real virtual calls. Adding implementations to a hot call site therefore changes the optimization strategy, not just the dispatch cost.
Common misconception: That inlining is about saving the cost of a call. The saved call is the smallest part; seeing through the call is the payoff.
What is deoptimization, and when does it happen?+
It is the runtime discarding compiled code whose assumptions stopped holding: a type profile invalidated by a new implementation, a class hierarchy change, a failed guard. The compiled frame carries enough state to rebuild interpreter frames, so execution continues at the same bytecode position, more slowly.
The failing point is an uncommon trap. Afterwards the method is re-profiled and can be recompiled for the new reality. A method that deoptimizes repeatedly is a performance smell: its profile keeps changing under the optimizer.
Common misconception: That deoptimization means the JIT made a mistake. It means the program changed; the JVM's ability to walk away from an assumption is exactly what allows the assumption to be made.
Why do Java benchmarks need warm-up, and what does JMH do about it?+
Cold code is interpreted and C2 needs both executions and compile time, so a one-shot timing measures the wrong phase. JMH forks a clean JVM, warms up by policy, keeps results alive with Blackholes so dead code elimination cannot delete the work, runs multiple iterations and reports statistics.
Hand-rolled nanoTime loops fail in predictable ways: unused results get eliminated, constant inputs get folded, the loop runs once, and nobody checks which tier was active. Warm-up is not gaming the measurement; it is the phase that production mostly lives in.
Follow-up: How would you benchmark a cold start instead, and what changes in the setup?