Hot methods and tiered compilation
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)HotSpot does not compile a method once and for all. It counts how often code runs and moves hot methods up through tiers: the interpreter first, then a quick compile by C1, then a strongly optimised compile by C2.
Invocation and loop counters decide what is hot
Each method has an invocation counter, which goes up on every call, and a back-edge counter, which goes up every time a loop inside it jumps back to its start. A back edge is that backward jump at the end of each loop round.
Example 1 · The real thresholds on HotSpot 21
java -XX:+PrintFlagsFinal -version | grep -E "Tier[34]|TieredCompilation|TieredStopAtLevel|CICompilerCount " intx CICompilerCount = 4 {product} {ergonomic}
intx Tier3BackEdgeThreshold = 60000 {product} {default}
intx Tier3CompileThreshold = 2000 {product} {default}
intx Tier3InvocationThreshold = 200 {product} {default}
intx Tier4BackEdgeThreshold = 40000 {product} {default}
intx Tier4CompileThreshold = 15000 {product} {default}
intx Tier4InvocationThreshold = 5000 {product} {default}
bool TieredCompilation = true {pd product} {default}
intx TieredStopAtLevel = 4 {product} {default}What this code does
-XX:+PrintFlagsFinallists every JVM option with its current value.{default}means nobody changed it;{ergonomic}means the JVM picked it for this machine. On Windows Command Prompt usefindstr Tierinstead ofgrep.CICompilerCount = 4is the number of compiler threads chosen for this machine with 12 logical CPUs; yours may differ. The thresholds are the same on Java 17 and 21.
Example 2 · A small model of the counters
class MethodCounters { final String name; int invocations = 0; int backEdges = 0; int level = 0; boolean loopCompiled = false;
MethodCounters(String name) { this.name = name; }}
public class CounterModelDemo { static final int TIER3_INVOCATIONS = 200; static final int TIER4_INVOCATIONS = 5000; static final int TIER3_BACK_EDGES = 60000;
static void call(MethodCounters m) { m.invocations++; if (m.level == 0 && m.invocations >= TIER3_INVOCATIONS) { m.level = 3; System.out.println(m.name + ": compile at level 3 (C1) after " + m.invocations + " calls"); } else if (m.level == 3 && m.invocations >= TIER4_INVOCATIONS) { m.level = 4; System.out.println(m.name + ": compile at level 4 (C2) after " + m.invocations + " calls"); } }
static void loopRound(MethodCounters m) { m.backEdges++; if (!m.loopCompiled && m.backEdges >= TIER3_BACK_EDGES) { m.loopCompiled = true; System.out.println(m.name + ": its loop is hot after " + m.backEdges + " rounds"); } }
public static void main(String[] args) { MethodCounters fare = new MethodCounters("fare"); // tiny, called a lot MethodCounters report = new MethodCounters("dailyReport"); // called once, long loop MethodCounters login = new MethodCounters("login"); // called a few times
for (int i = 0; i < 6000; i++) call(fare); call(report); for (int i = 0; i < 80_000; i++) loopRound(report); for (int i = 0; i < 50; i++) call(login);
System.out.println("fare: " + fare.invocations + " calls, level " + fare.level); System.out.println("dailyReport: " + report.invocations + " call, level " + report.level); System.out.println("login: " + login.invocations + " calls, level " + login.level); }}fare: compile at level 3 (C1) after 200 calls fare: compile at level 4 (C2) after 5000 calls dailyReport: its loop is hot after 60000 rounds fare: 6000 calls, level 4 dailyReport: 1 call, level 0 login: 50 calls, level 0
What this code does
farecrosses 200 calls and is queued for level 3, then crosses 5,000 and is queued for level 4.loginwith 50 calls never becomes hot and stays interpreted, which is fine: compiling it would save almost nothing.levelstarts at 0, which means interpreted.dailyReportis called only once, so its invocation counter never helps. Its loop counter crosses 60,000 rounds, and that is what triggers compilation of its loop (on-stack replacement, the last section).
When a counter passes a threshold, the JVM puts the method in a compile queue. On HotSpot for Java 17 and 21 the main defaults are 200 calls for the first compile (Tier3InvocationThreshold) and 5,000 calls for the optimised compile (Tier4InvocationThreshold). A loop needs about 60,000 rounds (Tier3BackEdgeThreshold). These numbers are a simplified picture. The real policy combines both counters and waits longer when the compile queue is long, so a busy JVM compiles a little later. Example 2 is a small model of the idea, not the real algorithm.
C1 and C2: a fast compiler and a strong one
C1, also called the client compiler, compiles quickly and does simple optimisations. C2, the server compiler, takes much longer to compile but produces much faster code. It inlines calls aggressively, simplifies loops and uses the profile to predict what the code will do.
Example 3 · C1 only versus the full tiered system
java -XX:TieredStopAtLevel=1 WarmUpDemojava WarmUpDemo$ java -XX:TieredStopAtLevel=1 WarmUpDemo Round 1: 7023 us (sum 4600002) Round 2: 4588 us (sum 4600002) Round 3: 5623 us (sum 4600002) Round 4: 4621 us (sum 4600002) Round 5: 4485 us (sum 4600002) Round 6: 5101 us (sum 4600002) Round 7: 4532 us (sum 4600002) Round 8: 4584 us (sum 4600002) $ java WarmUpDemo Round 1: 7089 us (sum 4600002) Round 2: 4340 us (sum 4600002) Round 3: 2754 us (sum 4600002) Round 4: 1814 us (sum 4600002) Round 5: 1933 us (sum 4600002) Round 6: 1797 us (sum 4600002) Round 7: 1909 us (sum 4600002) Round 8: 1765 us (sum 4600002)
What this code does
WarmUpDemois the program from the previous lesson. With C1 only, the time drops a little and then stays near 4.5 ms per round: C1 code is fast to produce but not deeply optimised.- With the normal setup, C2 takes over from round 3 or 4 and the rounds settle near 1.8 ms, about 2.5 times faster than C1 alone on this machine. Your numbers will differ.
A profile is the record the JVM keeps while code runs: how often each branch was taken and which classes reached each call. The interpreter and C1-compiled code collect it; C2 reads it. The two compilers solve different problems. C1 gives a fast first version within milliseconds, which helps startup. C2 spends more effort, but only on code that has proved it is really hot, which gives the best long-run speed.
Order of execution
A method gets hot
Tap the steps in the order they happen to one busy method.
Tiered compilation levels, simplified
Tiered compilation means a method moves up numbered levels as it gets hotter: level 0 (interpreter), then level 3 (C1 with profiling), then level 4 (C2). It is the default in HotSpot since Java 8.
Tiered compilation means a method moves up through numbered levels as it gets hotter. It is on by default in HotSpot since Java 8.
# C1 only: faster startup, lower peak speedjava -XX:TieredStopAtLevel=1 App# Turn tiering off: interpreter, then straight to C2java -XX:-TieredCompilation AppThe usual path is 0 → 3 → 4: interpreted, then C1 code that also records a profile, then C2 code built from that profile. A trivial method, such as a getter that only returns a field, goes 0 → 1, because there is nothing worth profiling. Level 2 is used when C2's queue is too long to take more work.
- Level 0: the interpreter.
- Level 1: C1 with full optimisation and no profiling.
- Level 2: C1 with a little profiling.
- Level 3: C1 with full profiling.
- Level 4: C2, full optimisation.
Watching compilation with -XX:+PrintCompilation
-XX:+PrintCompilation makes HotSpot print one line each time it compiles a method, and each time it retires a compiled version. It is a standard product flag, so it works without any unlock option.
Example 4 · A program to watch: train fares
public class TicketFare { // Fare for one train ticket: Rs 1.5 per km, minimum Rs 30, in whole rupees static int fare(int km) { int f = km * 3 / 2; return Math.max(f, 30); }
public static void main(String[] args) { long total = 0; for (int i = 0; i < 300_000; i++) { total += fare(i % 2000); } System.out.println("Total fares: Rs " + total); }}Total fares: Rs 449748000
What this code does
fareis tiny and is called 300,000 times, so it becomes hot very quickly.mainis called only once, but its loop runs 300,000 rounds. Watch what happens to both methods in the next example.
Example 5 · Reading -XX:+PrintCompilation output
java -XX:+PrintCompilation TicketFare | grep -E "TicketFare|Total"107 72 3 TicketFare::fare (13 bytes) 107 73 4 TicketFare::fare (13 bytes) 107 72 3 TicketFare::fare (13 bytes) made not entrant 109 74 % 3 TicketFare::main @ 4 (41 bytes) 110 75 3 TicketFare::main (41 bytes) 110 76 % 4 TicketFare::main @ 4 (41 bytes) 113 74 % 3 TicketFare::main @ 4 (41 bytes) made not entrant Total fares: Rs 449748000
What this code does
- Line 1: about 107 ms after start, compile #72 makes a level 3 (C1) version of
fare, whose bytecode is 13 bytes long. Line 2: compile #73 makes the level 4 (C2) version. Line 3: the level 3 version is retired withmade not entrantbecause the better one is ready. - The
%lines are OSR compiles of the loop inmain. The JVM also printed a normal level 3 compile ofmain, which is never used sincemainis not called again. Withoutgrepyou would also see a few hundred lines for JDK methods.
Each line has the columns listed below. A line ending in made not entrant means that compiled version must not be entered by new calls any more. After a level 4 line, the level 3 version of the same method is retired this way: a normal step up, not an error.
- Milliseconds since the JVM started, then the compile id (a running number).
- Flags:
%for on-stack replacement,sfor a synchronized method,!for a method with exception handlers,nfor a native method. - The tier level, 0 to 4.
- The method name and its size in bytes of bytecode; for OSR,
@ 4gives the bytecode position of the loop.
-Xlog:jit+compilation=debug prints the same lines through the unified logging system, with a log time stamp in front.On-stack replacement for long-running loops
On-stack replacement (OSR) switches a method from the interpreter to compiled code in the middle of a running loop, without waiting for the method to be called again.
Example 6 · On-stack replacement: @ 4 is the loop start
javap -c TicketFarejava -XX:+PrintCompilation TicketFare | grep "main @"$ javap -c TicketFare
...
public static void main(java.lang.String[]);
Code:
0: lconst_0
1: lstore_1
2: iconst_0
3: istore_3
4: iload_3
5: ldc #13 // int 300000
7: if_icmpge 28
10: lload_1
11: iload_3
12: sipush 2000
15: irem
16: invokestatic #14 // Method fare:(I)I
19: i2l
20: ladd
21: lstore_1
22: iinc 3, 1
25: goto 4
28: getstatic #20 // Field java/lang/System.out:Ljava/io/PrintStream;
...
$ java -XX:+PrintCompilation TicketFare | grep "main @"
109 74 % 3 TicketFare::main @ 4 (41 bytes)
110 76 % 4 TicketFare::main @ 4 (41 bytes)
113 74 % 3 TicketFare::main @ 4 (41 bytes) made not entrantWhat this code does
- In the bytecode of
main, position 4 isiload_3, the loop condition check. Thegoto 4at position 25 is the back edge: every loop round jumps back there. Bytecode is fromjavacof JDK 21 with--release 17. - The OSR compiles say
main @ 4: compiled code that is entered at position 4, in the middle of the running loop. The level 3 OSR version comes first, then the level 4 one, and the level 3 one is retired.
It matters for methods that are called once but loop for a long time, such as main with a big loop or a nightly batch job. A normal compile helps only the next call, which may never come. So when the back-edge counter of a loop gets high, HotSpot builds a special compiled version that starts at the top of that loop. The interpreter's local variables are copied into the compiled frame, and the loop carries on from the same round in machine code. In -XX:+PrintCompilation output, OSR compiles have the % flag and an @ with the bytecode position where the loop begins.
Next step
Check your understanding
12 quick questions