A model of tiered compilation thresholds
A teaching model: the JVM's real decisions also depend on loop counts and compiler load, so run with -XX:+PrintCompilation to see the true moments on your machine.
HotSpot starts by interpreting bytecode, counts which methods and loops are hot, and compiles those to machine code: quickly with C1, then aggressively with C2 using the profile it gathered. C2's big wins are inlining, escape analysis and speculative optimisations that are undone (deoptimised) if their assumptions break.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a program that counts how many times a small method is called inside a loop and prints the count at which it would cross the tier-3 and tier-4 thresholds (200 and 5000), for loop sizes 100, 1000 and 10000.
Rewrite a loop over a List<Shape> with three shape types so that each type is processed in its own loop (keeping call sites monomorphic), and show that the total area is the same.
Write a method that builds a StringBuilder, appends three values and returns the String, and explain in a comment whether the StringBuilder escapes.
Explain it without notes
Explain tiered compilation in HotSpot.
Why is inlining called the mother of all optimisations?
What is escape analysis and what does it enable?
What is deoptimisation, and when does it happen?
Expected output
call 1 -> tier 0: interpreted, counting calls
call 200 -> tier 3: C1 code that also collects a profile
call 5000 -> tier 4: C2 code optimised from the profile
sum of squares 1..6000 = 72018001000