Video in progress

Strong Middle ⚙️ JVM and memory

How do inlining and deoptimization work in the JIT, and how can they cause unexpected slowdowns on prod?

Inlining means copying the body of the called method into the caller, and it is the foundation of all other optimizations. C2 makes assumptions based on the profile. When an assumption breaks, deoptimization happens: the code goes back to the interpreter and is recompiled.

📖 Answer

From the profile, C2 knows which classes arrived at a call site:

  • monomorphic (always one implementation): inlined directly;
  • bimorphic (two): both are inlined behind an if;
  • megamorphic (3+): a virtual call, no inlining, and escape analysis doesn't work either.

The surprise goes like this. The service ran for an hour with only CardPayment, so PaymentProcessor.process was compiled as monomorphic. Then the first CryptoPayment arrived. The assumption broke, the method was made not entrant, and the code is profiled again. Latency spikes for a few seconds, and then everything runs a bit slower in the megamorphic version.

Another source is class hierarchy analysis (CHA): if an interface has a single implementation, C2 relies on that. If a new class is loaded at runtime (a plugin, a lazy proxy), deoptimization happens.

To see it:

-XX:+UnlockDiagnosticVMOptions -XX:+PrintCompilation -XX:+PrintInlining

Look for messages like made not entrant, hot method too big and too big. In JFR, the Deoptimization event also shows the reason.

The practical lesson: very big methods (FreqInlineSize, default 325 bytes of bytecode) are not inlined on a hot path. Splitting a hot-path method into smaller pieces sometimes gives a noticeable speedup, but only do it after you have measured.