Escape analysis
Escape analysis is a JIT optimization that asks whether an object can be seen outside the current compiled method. If it cannot escape, HotSpot may allocate it on the stack or explode it into registers and skip the heap object.
Detailed Explanation
new Point(1, 2) looks like a heap allocation. If the compiler proves the Point never stored in a field, never passed to an unknown method, and never returned, the object does not escape. Scalar replacement then stores x and y as locals. There is no header, no heap word, no young-gen traffic. Lock elision can also drop synchronized on a non-escaping object.
Escape analysis runs in C2 (and to a degree in other compilers). It is not a language guarantee. A debug println(point) or storing into a list makes the object escape, and the allocation returns. That is why a microbenchmark can flip when you add a log line.
Java's language model still says objects live on the heap. Escape analysis is an optimization you cannot code to, only benefit from. You write clear small objects. The JIT decides.
You reach for this knowledge when a profiler shows allocations that "should not matter" disappearing in hot loops, or when they suddenly appear after a refactor that stores the object. You do not write "stack-allocated" comments as if they were C. You do not disable escape analysis without a measured reason (-XX:-DoEscapeAnalysis).
The cost of an escaping temporary in a tight loop is allocation and GC. Records and small tuples in streams often escape because they are stored in a list or returned. A primitive loop does not. Valhalla value types (when they arrive) aim to make this a language-level property; until then, EA is best-effort.
Thread-local allocation already makes new cheap. EA is the next step: no object at all. It does not help objects that must be shared.
Code Examples
public class HotSum {
static long sum(int n) {
long total = 0;
for (int i = 0; i < n; i++) {
// If the JIT proves Pair does not escape, this may not allocate.
Pair p = new Pair(i, i + 1);
total += p.a() + p.b();
}
return total;
}
record Pair(int a, int b) {}
public static void main(String[] args) {
System.out.println(sum(3)); // prints: 9
}
}import java.util.ArrayList;
import java.util.List;
public class Escapes {
static List<Object> hold = new ArrayList<>();
static void pin(int n) {
Pair p = new Pair(n, n);
hold.add(p); // stored in a field-reachable list: escapes
}
record Pair(int a, int b) {}
public static void main(String[] args) {
pin(1);
System.out.println(hold.size()); // prints: 1
}
}Common Gotchas
Escape analysis is not a promise
a change that stores or publishes the object brings allocations back.
`synchronized` on a non-escaping object can be removed
do not use that as a lock with another thread.
There is no Java syntax for stack allocation
There is no Java syntax for stack allocation