Sub topic 15
Interpreter and JIT compilation
This chapter covers the last stage of the pipeline: how the JVM runs bytecode once classes are loaded, linked, and initialized. It assumes you can read simple javap -c output, know that each method call gets a stack frame, and can run java with command-line flags. It describes the HotSpot JVM that ships with Java 11.
Two ways to run the same bytecode
Bytecode is not machine code, so the CPU cannot run it directly. HotSpot uses two execution strategies and switches between them per method:
- The interpreter reads one bytecode instruction at a time and performs it. It starts immediately and needs no preparation, but each instruction costs many machine instructions.
- A JIT compiler (just-in-time compiler) translates a method's bytecode into native machine code while the program runs. Compiling takes time and memory, but the resulting code runs many times faster than interpretation.
The JVM does not compile everything. Most methods in a program run only a few times, and compiling them would cost more than it saves. HotSpot interprets first and compiles only the methods that prove to be hot, meaning they run often.
How HotSpot decides what is hot
Every method has counters that the interpreter updates:
- An invocation counter counts calls to the method.
- A back-edge counter counts how many times a loop inside the method jumps back to its start.
When the counters pass a threshold, the JVM queues the method for compilation on a background compiler thread. The program keeps running in the interpreter meanwhile. When compilation finishes, later calls to the method use the native code.
A method that is called once but loops millions of times never gets a second call. For that case HotSpot uses on-stack replacement (OSR). It compiles the loop, then swaps the running interpreted frame for a compiled one in the middle of the loop.
Tiered compilation and the two compilers
HotSpot ships two JIT compilers:
- C1 (the client compiler) compiles fast and applies light optimizations.
- C2 (the server compiler) compiles slowly and applies aggressive optimizations.
Since Java 8, tiered compilation is on by default and combines both. A method moves through numbered levels:
| Level | Executed by | Notes |
|---|---|---|
| 0 | Interpreter | Collects counters and some profile data |
| 1 | C1 | No profiling. Used for trivial methods that C2 could not improve |
| 2 | C1 | Limited profiling. Used when C2's queue is full |
| 3 | C1 | Full profiling. The usual first compiled level |
| 4 | C2 | Fully optimized, using the profile gathered at level 3 |
Level 3 code is slower than level 4 because it spends time recording profile data. That data is what lets C2 guess well. The JVM pays a short slowdown to gather the profile, then gets faster code.
Seeing compilation happen
The flag -XX:+PrintCompilation prints a line each time a method is compiled. Here is a program with a small, hot method:
public class HotLoop {
static int square(int x) {
return x * x;
}
public static void main(String[] args) {
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 50_000_000; i++) {
sum += square(i % 1000);
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("sum=" + sum + " time=" + ms + " ms");
}
}Compile it, then run it with compilation logging and filter for the interesting names:
$ javac HotLoop.java
$ java -XX:+PrintCompilation HotLoop | grep HotLoop
61 38 3 HotLoop::square (4 bytes)
62 41 % 3 HotLoop::main @ 8 (45 bytes)
75 47 4 HotLoop::square (4 bytes)
80 49 % 4 HotLoop::main @ 8 (45 bytes)The timestamps, IDs, and sizes on your machine will differ. The columns are:
- Milliseconds since JVM start.
- A compilation ID.
- Flags.
%marks an OSR compilation, andsmarks a synchronized method. - The tier level.
- The method name and its bytecode size. For OSR,
@ 8is the bytecode index of the loop.
square is 4 bytes of bytecode: iload_0, iload_0, imul, ireturn. It appears first at level 3, then at level 4. main appears with % because it is called once and runs a long loop.
Comparing modes
You can force the JVM into one strategy to see the effect:
| Flag | Effect |
|---|---|
| `-Xint` | Interpreter only. Nothing is compiled |
| `-XX:TieredStopAtLevel=1` | C1 only, with no profiling overhead |
| `-Xcomp` | Compile every method on first call. Useful for tests, rarely for production |
| `-XX:-TieredCompilation` | Interpreter plus C2 only |
Run HotLoop with -Xint and then with no flags. The interpreted run is typically many times slower. Use these flags to understand behavior, not as tuning advice.
What C2 does with profile data
C2 optimizes based on what the program actually did during profiling. Three optimizations matter most:
- Inlining copies a called method's body into the caller. This removes call overhead and lets other optimizations see across the call. By default HotSpot inlines small methods (under 35 bytes of bytecode) and larger ones up to 325 bytes if they are hot. That is one reason small getters and helpers are cheap.
- Devirtualization turns a virtual call into a direct one. The profile records which receiver classes appeared at a call site. If only one class ever appeared (a monomorphic site), C2 inlines that class's method behind a cheap type check. Two classes (bimorphic) are handled similarly. Many classes (megamorphic) force a slower table lookup and usually block inlining. C2 can also use class hierarchy analysis. If no loaded subclass overrides a method, the call can be treated as direct.
- Escape analysis checks whether an object ever leaves the method. If it does not, the JVM can avoid heap allocation by keeping its fields in registers, a technique called scalar replacement.
Deoptimization
C2's guesses can turn out wrong. A new subclass may be loaded that overrides an inlined method. A branch that was never taken may suddenly run. A type check may meet a new class. When this happens the JVM performs deoptimization. It discards the optimized code, rebuilds the interpreter frames from the compiled state, and continues in the interpreter. The method can later be recompiled with the new facts.
PrintCompilation shows this as made not entrant, which means no new calls will enter that compiled version:
$ java -XX:+PrintCompilation HotLoop | grep "made not entrant"A few such lines during startup are normal. Repeated deoptimization of the same method in steady state signals a problem such as a call site whose types keep changing.
Where compiled code lives
Native code is stored in the code cache, a region of memory outside the Java heap. Java 11 divides it into segments for non-method code, lightly optimized (profiled) code, and fully optimized code. The total size is set with -XX:ReservedCodeCacheSize. If the cache fills, the JVM stops compiling new methods and prints a warning. The program keeps running but slows down, because more of it stays in the interpreter. Long-running applications that load many classes are the usual cause.
Common mistakes
- Trusting a single cold timing. The first run includes interpretation, profiling, and compilation. Measure after warm-up.
- Assuming "Java is interpreted." After warm-up, hot code is native code, and in many programs it approaches the speed of compiled C or C++.
- Writing hand-inlined code for speed. Very large methods (over 8000 bytes of bytecode by default) are never compiled. Small, clear methods are what the JIT handles best.
- Reading
PrintCompilationas a profiler. It shows what was compiled and when, not where time is spent.
Exercise
You run a service for ten minutes. Its first few seconds are slow, then it speeds up. A colleague suggests this means the JVM is "caching results". Give the correct explanation, and name the tiers a hot method passes through and the flag you would use to watch it happen.
Show answer
The speed-up comes from JIT compilation, not result caching. At first, methods run in the interpreter (level 0), which also collects invocation and loop counters. When a method becomes hot it is compiled by C1 with profiling (level 3). If it stays hot, C2 recompiles it at level 4 using the profile, with optimizations such as inlining, devirtualization, and escape analysis. Loops in methods that are called only once are handled by on-stack replacement. Run the service with -XX:+PrintCompilation to see each compilation, its tier level, and any "made not entrant" lines that indicate deoptimization.