Sub topic 1
Starting out: the bytecode interpreter
Prerequisites
This chapter assumes basic Java programming, familiarity with JVM bytecode, and comfort running javac and java from a command line.
Starting with the bytecode interpreter
The Java compiler translates source code into bytecode stored in .class files. The HotSpot JVM initially runs that bytecode in an interpreter. The interpreter reads instructions and executes them one at a time.
Starting this way has a cost per instruction, but it avoids compiling every method before the program starts. Most methods may run only once, so compiling them would waste startup time and memory.
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);
}
}Why HotSpot compiles at run time
A just-in-time (JIT) compiler translates frequently executed bytecode into native machine code while the program runs. Native code can run much faster because it is specialized for the current machine and the behavior observed during execution.
HotSpot therefore uses a mixed strategy: interpret code at first, collect runtime information, and compile code that proves useful to optimize.
The two compilers: C1 and C2
HotSpot’s traditional tiered system uses two JIT compilers:
- C1, the client compiler, compiles quickly and applies relatively simple optimizations. It reduces the time spent interpreting.
- C2, the server compiler, compiles more slowly but uses detailed profiling to apply stronger optimizations, such as inlining and loop transformations.
Tiered compilation lets C1 provide an early speedup while C2 prepares highly optimized code for long-running methods.
> callout note > Compiled code is not automatically faster for every method. Compilation has a cost, and short-lived programs can finish before that cost is repaid.
How HotSpot decides a method is hot
HotSpot maintains execution counters. An invocation counter records method entries. A back-edge counter records jumps that return to an earlier bytecode position, usually a loop. When counters pass thresholds, HotSpot places the method on a compiler queue.
A method can be compiled at different tier levels. Level 0 is interpreted execution. Levels 1 through 3 generally use C1 with increasing profiling, and level 4 uses C2.
Long-running loops and on-stack replacement
A loop can become hot while its method is already running in the interpreter. On-stack replacement (OSR) replaces the current interpreted frame with compiled code at the loop, allowing execution to continue without restarting the method.
Exercise
Why might HotSpot use the interpreter before compiling a method?
Show answer
Interpretation avoids spending compilation time on methods that run only briefly, while counters identify code whose repeated execution can repay the compilation cost.