Command Palette

Search for a command to run...

Back to the lesson: Topic 14.4 — The JIT Compiler
Core Java · Example 3 of 3 Java 16+

Objects that escape and objects that don't

Same result, different cost once hot: compare the allocation rate of each method with JFR or -Xlog:gc on your own JDK, using a much larger n.

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.

01

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.

02

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.

03

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

01

Explain tiered compilation in HotSpot.

02

Why is inlining called the mother of all optimisations?

03

What is escape analysis and what does it enable?

04

What is deoptimisation, and when does it happen?

Objects that escape and objects that don't Java 16+
Sign in to run this example in your browser.

Expected output

no escape:   5150
escapes:     5150
points kept: 100, last Point[x=5050, y=100]