Sub topic 2
Why HotSpot compiles at run time
This chapter assumes you can read basic Java and run java and javac from a terminal. It also assumes you know that javac produces bytecode and that the JVM executes it. The previous chapter covered the bytecode interpreter. Here we ask why HotSpot does not stay with it, and why it compiles at run time instead of ahead of time.
The problem with interpretation alone
The HotSpot interpreter reads one bytecode at a time and runs a small piece of machine code for each one. It starts immediately, needs no analysis, and is simple to debug. It also has three costs:
- Every bytecode pays dispatch overhead. The interpreter must fetch it, decode it, and jump to its handler.
- Values move through the bytecode operand stack in memory. A CPU would normally keep them in registers.
- Each bytecode is handled on its own. The interpreter cannot combine
iload,iload, andiaddinto one machine add.
Interpreted code is commonly an order of magnitude or more slower than the same code compiled to native instructions. The exact gap depends on the workload. That gap is too large to accept for code that runs billions of times.
Why not compile everything up front?
Compiling all code to native form before the program starts sounds simple. That is ahead-of-time (AOT) compilation, and C and C++ toolchains work this way. HotSpot compiles while the program runs, which is called just-in-time (JIT) compilation. It does this for four reasons.
- Most code is cold. A typical application loads thousands of methods. Most run a few times, such as startup code, error handlers, and configuration parsing. Optimizing them costs more than it saves. Time spent compiling is time not spent running your program.
- Runtime facts are better than static guesses. At run time the JVM knows which classes are loaded, which branch is taken 99.9% of the time, and which concrete type shows up at a call site. A static compiler must assume the worst case.
- Java is dynamic. Classes can be loaded, generated, or replaced while the program runs. Reflection and
ClassLoadermake the full set of code impossible to know in advance. - The real CPU is known. The JIT can check which instruction set extensions the machine supports and use them. A binary built ahead of time usually targets a conservative baseline.
The result is a division of labor. The interpreter handles the large amount of code that runs rarely. The JIT compiler concentrates its effort on the small part that runs constantly. Programs typically spend most of their time in a small fraction of their code, so effort spent there pays off.
The last branch in the diagram, going back to the interpreter, is deoptimization. It is possible only because the JVM keeps the bytecode and the knowledge of how to interpret it. Later chapters cover it in detail.
Static compilation compared with JIT
| Aspect | Ahead-of-time compilation | HotSpot JIT |
|---|---|---|
| Start-up | Fast, since code is already native | Slower, since code starts interpreted |
| Peak speed | Limited by what can be proven statically | Can exploit run-time profile data |
| Memory | Native code is fixed in size | Needs a code cache and compiler working memory |
| Dynamic loading | Hard to optimize across | Handled by recompiling when assumptions break |
| Predictability | Same speed from the first call | Speed changes over time (warmup) |
The JIT trades a slower and less predictable start for higher peak performance. Long-running servers benefit most from this trade. Short command-line tools benefit least.
Seeing the effect
The following program runs the same loop five times and prints how long each round takes. Compile it with javac and run it twice.
public class WhyJit {
static int work(int x) {
return (x * 31) ^ (x >>> 3);
}
public static void main(String[] args) {
for (int round = 1; round <= 5; round++) {
long start = System.nanoTime();
int acc = 0;
for (int i = 0; i < 20_000_000; i++) {
acc += work(i);
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("round " + round + ": " + ms + " ms (acc=" + acc + ")");
}
}
}javac WhyJit.java
# Default: interpreter plus JIT compilers
java WhyJit
# Interpreter only: the JIT is switched off
java -Xint WhyJitOn a typical machine you should see this:
- With the default settings, the first round is the slowest. Compilation is still happening during it. Later rounds are much faster and roughly equal to one another.
- With
-Xint, every round is slow and about the same. Nothing ever gets faster, because nothing is ever compiled.
Your absolute numbers will differ. The pattern matters: a slow start, then a speed-up, then a steady state. That pattern is warmup, and a later chapter returns to it.
The program prints acc so the computed result is used. If a program computed a value and never used it, the compiler would be free to remove the whole computation. Benchmarks get this wrong often.
What the JIT can do that a static compiler cannot
Here is a concrete case. Suppose a method calls shape.area() on an interface type. A static compiler sees only the interface and must emit a virtual call. HotSpot can observe that, so far, only one class has been loaded that implements area(). It can then treat the call as direct and inline the body. If a second implementation is loaded later, HotSpot throws away that compiled code and recompiles. This kind of optimization depends on knowing the current state of the running program.
A second case is a branch that has never been taken. The JIT can leave the code for that branch out entirely. If the branch is ever taken, the JVM falls back to the interpreter for that execution.
Costs of runtime compilation
Choosing JIT also brings costs you should recognize when you see them:
- CPU time for compilation. Compiler threads run alongside your application and compete for cores. On a container limited to one CPU this competition is easy to notice.
- Memory. Compiled code is stored in the code cache. The compiler also needs temporary memory while it works.
- Warmup. Performance during the first seconds or minutes is not representative of steady state.
- Variance. Two runs of the same program can compile methods in a different order, so timings differ.
Summary of the design idea
HotSpot assumes that a program's time is concentrated in a small set of methods and loops. It starts everything in the interpreter because that is cheap. It then spends compilation effort only where measurement shows it will pay off, and it uses that same measurement to optimize more aggressively than a static compiler safely could. The following chapters explain how HotSpot measures hotness, and which compilers do the work.
Exercise
A short command-line tool runs for 200 ms and then exits. A colleague proposes tuning the JVM for the highest possible peak performance. Based on this chapter, why might that effort be wasted, and what would you check first?
Show answer
A 200 ms run spends almost all its time in the interpreter and in early compilation, so it never reaches the steady state where peak optimizations pay off. Most methods never become hot enough to be compiled at all. Peak-performance tuning therefore has little effect. Check start-up behavior first, such as how many classes are loaded and whether the JIT compiler threads compete with the application for CPU. Comparing a default run with -Xint also shows how much the JIT contributes at that run length.
Exercise
Name two reasons HotSpot can generate better code than a static compiler for the same Java method.
Show answer
First, it uses run-time profile data, such as which branches are taken and which concrete types appear at a call site. Second, it knows the current set of loaded classes and the actual CPU, so it can inline or devirtualize calls and use available instruction set extensions. It can undo these decisions by deoptimizing if the assumptions later fail.