Deoptimization: when the JIT changes its mind
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Deoptimization is the JVM throwing away a piece of JIT-compiled code and going back to the interpreter, because an assumption the compiler made is no longer true. It is what makes the JIT's bold guesses safe.
The JIT makes guesses from what it has seen so far
C2 compiles from the profile, the record of what the code has done so far. If a branch was never taken, C2 may leave it out of the compiled code. If only one class ever reached a call, C2 may inline that class's method.
Example 1 · A branch the JIT has never seen taken
public class LibraryFineDemo { // Fine for returning a library book: Rs 5 per late day, capped at Rs 200 static int fine(int daysLate) { if (daysLate > 0) { return Math.min(daysLate * 5, 200); } return 0; }
static long dayTotal(int[] daysLate) { long total = 0; for (int d : daysLate) { total += fine(d); } return total; }
public static void main(String[] args) { int[] onTime = new int[100]; // all zeros: nobody is late int[] someLate = new int[100]; for (int i = 0; i < someLate.length; i++) { someLate[i] = i % 4; // 0, 1, 2 or 3 days late }
long total = 0; for (int day = 0; day < 5_000; day++) { total += dayTotal(onTime); } System.out.println("After 5000 on-time days: Rs " + total);
for (int day = 0; day < 5_000; day++) { total += dayTotal(someLate); } System.out.println("After 5000 days with late returns: Rs " + total); }}After 5000 on-time days: Rs 0 After 5000 days with late returns: Rs 3750000
What this code does
- For the first 5,000 days every
daysLateis 0, so the profile says theifinfineis never true. By thenfineanddayTotalare C2-compiled with that guess. - In the second phase three of every four returns are late. The answer is still exactly right: 25 students each pay Rs 5, Rs 10 and Rs 15 per day, which is Rs 750 a day for 5,000 days.
Example 2 · Watching the uncommon trap fire
java -XX:+PrintCompilation -Xlog:deoptimization=debug LibraryFineDemo | grep -E "LibraryFine|After|deopt"47 69 3 LibraryFineDemo::fine (16 bytes) 48 70 4 LibraryFineDemo::fine (16 bytes) 48 71 3 LibraryFineDemo::dayTotal (41 bytes) 48 69 3 LibraryFineDemo::fine (16 bytes) made not entrant 48 72 % 4 LibraryFineDemo::dayTotal @ 11 (41 bytes) After 5000 on-time days: Rs 0 60 140 4 LibraryFineDemo::dayTotal (41 bytes) [0.061s][debug][deoptimization] cid= 70 level=4 LibraryFineDemo.fine(I)I trap_bci=1 unstable_if reinterpret pc=0x0000019487ad43e0 relative_pc=0x0000000000000040 61 70 4 LibraryFineDemo::fine (16 bytes) made not entrant 63 71 3 LibraryFineDemo::dayTotal (41 bytes) made not entrant 63 142 4 LibraryFineDemo::fine (16 bytes) [0.063s][debug][deoptimization] cid= 72 osr level=4 LibraryFineDemo.fine(I)I trap_bci=1 osr_bci=11 unstable_if reinterpret pc=0x0000019487ad4b6c relative_pc=0x00000000000001cc 63 72 % 4 LibraryFineDemo::dayTotal @ 11 (41 bytes) made not entrant After 5000 days with late returns: Rs 3750000
What this code does
- Compile #70 is the C2 version of
fine. Right after the second phase starts, the log showstrap_bci=1 unstable_if: bytecode 1 offineis theifleofif (daysLate > 0), the branch C2 had left out. Then #70 ismade not entrant, and #142 is a fresh C2 compile that includes the late-fee code. - The OSR version #72 of
dayTotalhadfineinlined, so it hit the same trap and was thrown away too. One JDK compile line that was printed in the middle of a program line has been removed.
This is called speculative optimisation: optimising for a guess about the future. In place of the left-out case, C2 puts an uncommon trap: a cheap check that, if the unexpected case ever happens, stops the compiled code and hands control back to the JVM. The guess is never allowed to give a wrong answer.
Example 1 trains fine() on books that are always returned on time, so daysLate > 0 is never true during profiling. Example 2 shows the trap firing the first time a book comes back late: unstable_if is HotSpot's name for a trap on an if that went the "impossible" way.
Loading a new subclass can break a guess
Class hierarchy analysis (CHA) is how C2 uses the classes loaded so far. If an abstract method has only one loaded implementation, C2 can call or inline that one directly, with no type check at all.
Example 3 · A new subclass arrives after warm-up
abstract class Ticket { abstract int fare(int km);}
class SleeperTicket extends Ticket { int fare(int km) { return km + 50; }}
class AcTicket extends Ticket { int fare(int km) { return km * 3 + 100; }}
class TicketCounter { static Ticket acTicket() { return new AcTicket(); // AcTicket is loaded only when this runs }}
public class DeoptDemo { static long totalFare(Ticket t, int trips) { long sum = 0; for (int i = 0; i < trips; i++) { sum += t.fare(i % 500); } return sum; }
public static void main(String[] args) { Ticket sleeper = new SleeperTicket(); long a = 0; for (int round = 0; round < 20_000; round++) { a += totalFare(sleeper, 100); } System.out.println("Sleeper total: " + a);
Ticket ac = TicketCounter.acTicket(); long b = 0; for (int round = 0; round < 20_000; round++) { b += totalFare(ac, 100); } System.out.println("AC total: " + b); }}Sleeper total: 199000000 AC total: 497000000
What this code does
- For the first phase only
SleeperTicketis loaded, soTicket.farehas a single implementation and C2 can call it directly insidetotalFare. AcTicketis created in a separate class,TicketCounter, so it is loaded only whenacTicket()first runs. The totals are correct either way: deoptimization changes speed, never results.
Example 4 · Class loading invalidates compiled code
java -Xlog:class+load -XX:+PrintCompilation DeoptDemo | grep -E "Ticket|totalFare|total:"[0.133s][info][class,load] Ticket source: file:/.../ [0.135s][info][class,load] SleeperTicket source: file:/.../ 136 74 3 SleeperTicket::fare (5 bytes) 136 75 4 SleeperTicket::fare (5 bytes) 136 74 3 SleeperTicket::fare (5 bytes) made not entrant 136 76 3 DeoptDemo::totalFare (33 bytes) 137 77 % 4 DeoptDemo::totalFare @ 5 (33 bytes) 140 78 4 DeoptDemo::totalFare (33 bytes) 144 76 3 DeoptDemo::totalFare (33 bytes) made not entrant Sleeper total: 199000000 [0.176s][info][class,load] TicketCounter source: file:/.../ [0.183s][info][class,load] AcTicket source: file:/.../ 183 77 % 4 DeoptDemo::totalFare @ 5 (33 bytes) made not entrant 183 78 4 DeoptDemo::totalFare (33 bytes) made not entrant 183 140 3 AcTicket::fare (7 bytes) 183 141 % 4 DeoptDemo::totalFare @ 5 (33 bytes) 189 142 4 AcTicket::fare (7 bytes) 189 140 3 AcTicket::fare (7 bytes) made not entrant 189 143 4 DeoptDemo::totalFare (33 bytes) AC total: 497000000
What this code does
- Right after
AcTicketis loaded (0.183 s), both C2 versions oftotalFare, #77 (OSR) and #78, aremade not entrant, before anyAcTicketfare was even calculated. They depended on "SleeperTicketis the onlyTicket". - New compiles #141 and #143 follow, built for a world with two ticket types. File paths in the class loading lines are trimmed with
.../.
It records a dependency: "this code is valid only while no other subclass exists". Java loads classes lazily, when they are first needed. So a new subclass can appear at any time, for example a new AcTicket type after hours of SleeperTicket traffic. When that class is loaded, the JVM finds every compiled method that depended on the old picture and marks it invalid at once, before any AcTicket object even reaches it.
This is why plugins, new features behind a flag, or the first use of a rare class can cause a short burst of deoptimizations in a long-running service.
Going back to the interpreter and recompiling
Deoptimization means the JVM throws away compiled code whose guess turned out wrong and continues the same method in the interpreter, from exactly the same point.
When a trap fires or a dependency breaks, the JVM deoptimizes: it rebuilds the state of each affected call (local variables, operand stack, position) as interpreter frames, and the method continues in the interpreter from exactly the same point.
Example 5 · The cost: a short slow patch, then recovery
abstract class Ticket { abstract int fare(int km);}
class SleeperTicket extends Ticket { int fare(int km) { return km + 50; }}
class AcTicket extends Ticket { int fare(int km) { return km * 3 + 100; }}
class TicketCounter { static Ticket acTicket() { return new AcTicket(); // AcTicket is loaded only when this runs }}
public class DeoptTimingDemo { static long totalFare(Ticket t, int trips) { long sum = 0; for (int i = 0; i < trips; i++) { sum += t.fare(i % 500); } return sum; }
static long checksum = 0;
// Time one batch of 2,000 calls, in microseconds static long batch(Ticket t) { long start = System.nanoTime(); for (int k = 0; k < 2_000; k++) { checksum += totalFare(t, 100); } return (System.nanoTime() - start) / 1_000; }
public static void main(String[] args) { Ticket sleeper = new SleeperTicket(); for (int b = 1; b <= 5; b++) { System.out.println("Sleeper batch " + b + ": " + batch(sleeper) + " us"); } Ticket ac = TicketCounter.acTicket(); for (int b = 1; b <= 5; b++) { System.out.println("AC batch " + b + ": " + batch(ac) + " us"); } System.out.println("Checksum: " + checksum); }}Sleeper batch 1: 2727 us Sleeper batch 2: 2430 us Sleeper batch 3: 687 us Sleeper batch 4: 334 us Sleeper batch 5: 675 us AC batch 1: 9190 us AC batch 2: 440 us AC batch 3: 363 us AC batch 4: 366 us AC batch 5: 367 us Checksum: 348000000
What this code does
- Sleeper batches warm up from about 2.7 ms to about 0.3 to 0.7 ms. The first AC batch jumps to 9 ms:
totalFarewas deoptimized back to the interpreter, andAcTicket.fareitself is brand new and not compiled yet. - By AC batch 2 the methods are recompiled and the speed is back to normal. A single deoptimization costs milliseconds, not minutes. Your numbers will differ.
Your program never notices, except that it is slower for a moment. The profile now includes the new case. The method becomes hot again and is recompiled, this time without the broken guess, and it gets a new compile id.
Deoptimization is normal and usually rare. It becomes a problem only if it repeats again and again, for example when a branch flips between "never" and "often". HotSpot has limits for this: after too many traps at one place, it stops guessing there and compiles the general code.
made not entrant in compilation output
In -XX:+PrintCompilation output, made not entrant marks a compiled version that new calls may no longer enter.
Example 6 · Telling tier-ups from deoptimizations
import java.util.HashMap;import java.util.Map;
public class LogReaderDemo { public static void main(String[] args) { String[] log = { "136 75 4 SleeperTicket::fare (5 bytes)", "136 74 3 SleeperTicket::fare (5 bytes) made not entrant", "140 78 4 DeoptDemo::totalFare (33 bytes)", "144 76 3 DeoptDemo::totalFare (33 bytes) made not entrant", "183 78 4 DeoptDemo::totalFare (33 bytes) made not entrant", "189 142 4 AcTicket::fare (7 bytes)", "189 140 3 AcTicket::fare (7 bytes) made not entrant" }; Map<String, Integer> best = new HashMap<>(); // highest live level per method int tierUps = 0; int deopts = 0;
for (String line : log) { String[] t = line.replace(" % ", " ").trim().split("\\s+"); int level = Integer.parseInt(t[2]); String method = t[3]; if (!line.endsWith("made not entrant")) { best.merge(method, level, Math::max); continue; } if (level < best.getOrDefault(method, 0)) { System.out.println("tier-up: " + method + " level " + level + " retired"); tierUps++; } else { System.out.println("deoptimization: " + method + " level " + level + " thrown away"); best.remove(method); deopts++; } } System.out.println(tierUps + " tier-ups, " + deopts + " deoptimization"); }}tier-up: SleeperTicket::fare level 3 retired tier-up: DeoptDemo::totalFare level 3 retired deoptimization: DeoptDemo::totalFare level 4 thrown away tier-up: AcTicket::fare level 3 retired 3 tier-ups, 1 deoptimization
What this code does
- The log lines come from the run in Example 4. The program remembers the highest live level per method. A retired version below that level is a tier-up; a retired version at the top level is a deoptimization.
- This is a simplified reading rule, good enough for most logs. Lower-level code can also be invalidated by class loading, which the rule would count as a tier-up.
A thread that is in the middle of running it is switched to the interpreter when needed; once nothing uses the old version, its code cache memory is freed later. The same words appear for two very different events:
- A level 3 version retired after a level 4 version of the same method appeared: a normal tier-up.
- A level 4 (C2) version retired: a deoptimization. The JIT threw away its best code, and a new compile id usually follows.
- With
-Xlog:deoptimization=debug(Java 17 and later) HotSpot also prints the reason for traps, such asunstable_iforclass_check. - A few deoptimizations after startup or after a new feature is used are normal. A steady stream of them for the same method is worth investigating.
Next step
Check your understanding
12 quick questions