Java / JVM Architecture (Java21) Interview questions
How does escape analysis enable stack allocation optimizations?
Escape analysis is a C2 JIT optimization that determines whether an object created inside a method can ever be referenced, or "escape," outside that method or thread.
void compute() { // 'point' never leaves this method or gets stored anywhere else Point point = new Point(1, 2); int sum = point.x + point.y; System.out.println(sum); }
Since point in this example never escapes compute(), the JIT can apply scalar replacement: instead of allocating a real Point object on the heap, it treats the object's fields as independent local variables that live directly on the stack, or even just in registers, skipping heap allocation entirely.
The JIT can also apply lock elision to non-escaping objects, removing synchronization overhead on a lock that, by construction, no other thread could ever contend for.
Both optimizations reduce GC pressure and lock overhead, but they only kick in once C2 has enough profiling data to prove the object truly never escapes - they never apply to the interpreter or to C1-only compiled code.
More Related questions...