Sub topic 2
Tiered Compilation: Levels 0 to 4
Assume you know basic Java, bytecode, and command-line use of java. HotSpot begins by interpreting bytecode. It then compiles code that runs often, called hot code, into native machine code.
Tiered compilation: levels 0 to 4
Tiered compilation uses the fast C1 compiler for early optimized code and the slower, more powerful C2 compiler for code that stays hot.
| Level | Execution or compiler mode | Main purpose |
|---|---|---|
| 0 | Interpreter | Start execution and collect basic counts |
| 1 | C1, limited profiling | Produce quick native code |
| 2 | C1, limited profiling | Compile with some profiling |
| 3 | C1, full profiling | Gather detailed data for C2 |
| 4 | C2 | Apply expensive, aggressive optimizations |
The default tiered path is often level 0 to level 3 to level 4. Some methods use levels 1 or 2 when quick compilation matters more than detailed profiling.
How methods move between tiers
Invocation counters record method calls. Back-edge counters record loop iterations. When a counter passes a threshold, HotSpot places the method, or a loop, on a compiler queue.
A long-running loop can be compiled while it is already running. This process is on-stack replacement, or OSR. The JVM transfers the active loop from interpreted execution into compiled code instead of waiting for the method to return and be called again.
Watching the JIT with `PrintCompilation`
Use this small program to create hot methods and a hot loop:
public class HotLoop {
static int square(int x) {
return x * x;
}
public static void main(String[] args) {
long sum = 0;
for (int i = 0; i < 50_000_000; i++) {
sum += square(i % 1000);
}
System.out.println(sum);
}
}Run:
javac HotLoop.java
java -XX:+PrintCompilation HotLoopThe output includes a compilation ID, method name, and compilation level. An entry such as level 3 indicates C1 code with profiling. Level 4 indicates C2 code. An OSR marker identifies compilation entered from an already-running loop. Later output can show earlier code becoming not entrant when newer code replaces it.
Profiling and inlining
While code runs, HotSpot records receiver types, branch frequencies, and call behavior. C2 uses this profile to choose optimizations.
Inlining replaces a method call with the method body. For example, HotSpot may inline square into main. This removes call overhead and exposes the multiplication to other optimizations, such as constant propagation and loop optimization. Inlining depends on method size, call frequency, and the runtime types observed.
Exercise
Which level normally represents C2-compiled code?
Show answer
Level 4. Levels 1 through 3 are C1 compilation levels, while level 0 is interpretation.