Sub topic 3
The two compilers: C1 and C2
This chapter assumes you can read basic Java and run java from a terminal. It also assumes you know that Java source compiles to bytecode, and that HotSpot first runs that bytecode in an interpreter. The previous chapters covered why HotSpot compiles hot code at run time. This chapter covers the two compilers that do the work.
Two compilers, two goals
HotSpot ships with two just-in-time (JIT) compilers. Both turn bytecode into native machine code, but they make opposite trade-offs.
- C1 is also called the client compiler. It compiles quickly and applies a modest set of optimizations. The code it produces is much faster than interpreting, but not the fastest possible.
- C2 is also called the server compiler, or "opto" in the source tree. It compiles slowly, uses a lot of memory and CPU time, and applies aggressive optimizations. The code it produces is the fastest HotSpot can generate.
Neither compiler is better in every situation. A method that runs a few thousand times is not worth an expensive C2 compile. A method that runs billions of times is. HotSpot uses both so that it can pick the right one for each method.
What C1 does
C1 is a simple, fast compiler. It builds a high-level intermediate representation (IR) of the method, in static single assignment (SSA) form. It then lowers that to a low-level IR and allocates registers with a linear-scan allocator, which is fast but not optimal.
Its optimizations are limited to cheap ones:
- Constant folding, such as replacing
2 * 8with16. - Simple dead-code elimination and null-check elimination.
- Inlining of small methods, and of methods that cannot be overridden.
- Basic range-check elimination for array accesses.
C1 does not use runtime type profiles to make speculative guesses. It does not do escape analysis and does not perform aggressive loop transformations. That restraint is why it finishes quickly.
C1 can also add profiling code to the native code it emits. The interpreter and C1-compiled code collect the data C2 will later rely on. The tiers chapter covers when C1 does this.
What C2 does
C2 uses a different IR, called a "sea of nodes" graph. In it, data flow and control flow are both edges between nodes, and the compiler is free to reorder operations that do not depend on each other. It uses a graph-coloring register allocator, which usually produces better register assignments than linear scan but costs more compile time.
C2 applies everything C1 does, plus optimizations that depend on knowing how the program actually behaved:
- Profile-guided inlining. If a call site has only ever seen one receiver type, C2 can inline that target and guard the assumption.
- Escape analysis. If an object never leaves a method, C2 can avoid allocating it on the heap, or replace its fields with local values (scalar replacement).
- Loop optimizations. These include unrolling, loop-invariant code motion, and range-check elimination.
- Lock elision and coarsening. C2 removes locks on objects that cannot be shared between threads.
- Speculative optimizations. C2 drops branches that the profile says were never taken. If a dropped branch is later needed, the code deoptimizes. A later chapter covers this.
Because C2 relies on profile data, it should not compile a method until that data exists. This is the main reason a method is not compiled by C2 immediately.
Comparing them
| Property | C1 | C2 |
|---|---|---|
| Nickname | Client compiler | Server compiler |
| Compile speed | Fast | Slow |
| Memory use while compiling | Low | High |
| Code quality | Good | Best |
| Uses type and branch profiles | No (it may collect them) | Yes |
| Escape analysis | No | Yes |
| Register allocator | Linear scan | Graph coloring |
| Tiers it serves in tiered mode | 1, 2, 3 | 4 |
Seeing the difference
Run the program below, which wraps the hot loop from the topic's example in a timer. It prints elapsed time so you can compare configurations.
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 + " in " + ms + " ms");
}
}Compile it once, then run it in four modes:
javac HotLoop.java
# Default: tiered, both compilers available
java HotLoop
# C1 only (tiered, stop at level 1)
java -XX:TieredStopAtLevel=1 HotLoop
# C2 only (tiered compilation off)
java -XX:-TieredCompilation HotLoop
# Interpreter only, as a baseline
java -Xint HotLoopExpect -Xint to be far slower than the other three. The C1-only and default runs can be close on a program this small, because the loop body is trivial and the run is short. The difference becomes clearer on longer-running programs, where C2's extra work pays off. Absolute times depend on your machine, so compare ratios, not raw numbers.
To see which compiler handled a method, add -XX:+PrintCompilation. In the output, a number in the fifth column such as 3 or 4 is the tier. Tier 4 is C2. Tiers 1 to 3 are C1.
java -XX:+PrintCompilation HotLoop | grep squareWith -XX:TieredStopAtLevel=1, you will see square only at level 1. With -XX:-TieredCompilation, the tier column is absent and C2 compiles the method.
How the two work together
Tiered compilation, the default since JDK 8, combines the two compilers. A method starts in the interpreter. When it becomes warm, C1 compiles it quickly, so the program speeds up early. While it runs, profile data accumulates. If the method becomes very hot, C2 recompiles it using that data. The next chapters cover the counters, thresholds, and exact paths.
This design gives you C1's fast startup and C2's peak performance. Before tiered compilation existed, you had to pick one: the client VM started faster, and the server VM peaked higher.
When to limit the compilers
The default is right for most long-running services. Two cases are worth knowing about.
- Short-lived programs and command-line tools. If the process lives for a second or two, C2 may never finish a useful compile.
-XX:TieredStopAtLevel=1avoids C2's CPU and memory cost and often improves total run time. - Constrained containers. C2 compiles run on background threads and can use noticeable memory and CPU. Restricting to C1 reduces that footprint at the cost of peak speed.
Common errors
- Assuming C2 always beats C1. For code that runs briefly, C1 output is often the better total result, because C2's compile time is never repaid.
- Benchmarking with a single short run. You measure interpreter and C1 code and call it "Java's speed". A later chapter covers warmup in detail.
- Thinking
-serverselects C2. In JDK 11 it does nothing on 64-bit builds. - Reading tier 4 as "just C1 with more optimization". C2 is a separate compiler with its own IR and its own register allocator.
Exercise
A command-line tool starts, parses a file, and exits in about 400 ms. A teammate suggests running it with -XX:TieredStopAtLevel=1. Is this reasonable, and why?
Show answer
Yes, it is reasonable. In a run this short, few methods become hot enough for C2 to compile them, and any C2 compiles that do start use CPU and memory on background threads without time to repay that cost. Limiting HotSpot to C1 gives fast compiles and good code, so total run time often drops. You should still measure both settings, since the effect depends on the workload.
Exercise
Name two optimizations that C2 performs but C1 does not, and say what C2 needs in order to perform the first one.
Show answer
Escape analysis and profile-guided speculative inlining (also acceptable: loop unrolling with aggressive loop transformations, or lock elision). Speculative inlining needs profile data collected earlier, such as the receiver types seen at a call site, which is why C2 compiles a method only after the interpreter or C1 has gathered it.