Skip to lesson

Escape analysis in simple terms

A loop creates millions of small temporary objects, such as a point or a price pair, and each one needs heap memory. Often the JVM can avoid that cost completely. How does it decide?

An object escapes when it leaves the method or thread

Escape analysis is a check by the C2 compiler on whether an object can be reached from outside the method, or the thread, that created it. An object that does not escape may never be created on the heap.

An object escapes when a reference to it can be reached from outside the method that created it. HotSpot sorts objects into three groups, listed after the code.

Java
static int staysInside(int price) {     // no escape    Bill b = new Bill(price, 30);    return b.total();}
static Bill returned(int price) {       // argument escape    return new Bill(price, 30);}
static int storedGlobally(int price) {  // global escape    Bill b = new Bill(price, 30);    lastBill = b;                       // a static field    return b.total();}

Example 1 · Which objects really get allocated?

EscapeKindsDemo.javaJava
import java.lang.management.ManagementFactory;
class Bill {    final int price;    final int delivery;
    Bill(int price, int delivery) {        this.price = price;        this.delivery = delivery;    }
    int total() {        return price + delivery;    }}
public class EscapeKindsDemo {    static Bill lastBill;
    // 1. Stays inside: the Bill is used and forgotten    static int staysInside(int price) {        Bill b = new Bill(price, 30);        return b.total();    }
    // 2. Returned to the caller: escapes this method    static Bill returned(int price) {        return new Bill(price, 30);    }
    // 3. Stored in a static field: escapes to the whole program    static int storedGlobally(int price) {        Bill b = new Bill(price, 30);        lastBill = b;        return b.total();    }
    static long measureKb(Runnable work) {        com.sun.management.ThreadMXBean mx =                (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();        long before = mx.getCurrentThreadAllocatedBytes();        work.run();        return (mx.getCurrentThreadAllocatedBytes() - before) / 1024;    }
    static long sink;
    public static void main(String[] args) {        Runnable a = () -> { for (int i = 0; i < 100_000; i++) sink += staysInside(i % 400); };        Runnable b = () -> { for (int i = 0; i < 100_000; i++) sink += returned(i % 400).total(); };        Runnable c = () -> { for (int i = 0; i < 100_000; i++) sink += storedGlobally(i % 400); };
        for (int warm = 0; warm < 20; warm++) {            a.run();            b.run();            c.run();        }        System.out.println("Stays inside:      " + measureKb(a) + " KB");        System.out.println("Returned:          " + measureKb(b) + " KB");        System.out.println("Stored in a field: " + measureKb(c) + " KB");    }}
Sample output
Stays inside:      0 KB
Returned:          0 KB
Stored in a field: 2343 KB

What this code does

  • After 20 warm-up runs of each loop, the JIT has compiled them. Then each loop creates 100,000 Bill objects in the source. "Stays inside" allocated nothing: every Bill was scalar replaced.
  • "Returned" also allocated nothing: returned is tiny, so it was inlined into the loop, and after inlining the Bill never leaves the compiled code. "Stored in a field" escapes globally, so all 100,000 objects were really created: 2,343 KB, 24 bytes each.
  • No escape: the object is created, used and forgotten inside the method.
  • Argument escape: the object is passed to another method or returned, but no other thread can reach it.
  • Global escape: the object is stored in a static field, in a field of an escaping object, or handed to another thread.

C2 does this analysis after inlining. So an object returned by a small method that was inlined into its caller may not escape the caller's compiled code (Example 1 shows it).

Predict the output

Does the object escape?

Pick the kind of escape for the Money object in each snippet.

Round 1 of 3

The object is used and forgotten inside the method.

static int priceWithTax(int price) {
Money m = new Money(price, 18);
return m.total();
}

Scalar replacement: fields kept in registers instead of the heap

Scalar replacement means C2 does not create a non-escaping object at all. It keeps the object's fields as plain local values, usually in CPU registers. A scalar here is a single primitive or reference value, such as one int field.

Example 2 · Scalar replacement kicks in after compilation

EscapeDemo.javaJava
import java.lang.management.ManagementFactory;
class Bill {    final int price;    final int delivery;
    Bill(int price, int delivery) {        this.price = price;        this.delivery = delivery;    }
    int total() {        return price + delivery;    }}
public class EscapeDemo {    // The Bill object never leaves this method: it does not escape    static int orderTotal(int price) {        Bill b = new Bill(price, 30);        return b.total();    }
    static long round() {        long sum = 0;        for (int i = 0; i < 100_000; i++) {            sum += orderTotal(100 + i % 400);        }        return sum;    }
    public static void main(String[] args) {        com.sun.management.ThreadMXBean mx =                (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();        for (int r = 1; r <= 6; r++) {            long before = mx.getCurrentThreadAllocatedBytes();            long sum = round();            long kb = (mx.getCurrentThreadAllocatedBytes() - before) / 1024;            System.out.println("Round " + r + ": allocated " + kb + " KB (sum " + sum + ")");        }    }}
Sample output
Round 1: allocated 441 KB (sum 32950000)
Round 2: allocated 0 KB (sum 32950000)
Round 3: allocated 0 KB (sum 32950000)
Round 4: allocated 0 KB (sum 32950000)
Round 5: allocated 0 KB (sum 32950000)
Round 6: allocated 0 KB (sum 32950000)

What this code does

  • Round 1 allocated a few hundred KB while orderTotal was still interpreted or compiled by C1. From round 2, with the C2 version running, the 100,000 Bill objects per round take no heap memory at all.
  • The sum is the same in every round. Scalar replacement changes where the values live, never the result. Allocation numbers can differ a little on your machine.

Example 3 · The same program with escape analysis off

Terminal
java -XX:-DoEscapeAnalysis EscapeDemo
Sample output
$ java -XX:-DoEscapeAnalysis EscapeDemo
Round 1: allocated 2346 KB (sum 32950000)
Round 2: allocated 2343 KB (sum 32950000)
Round 3: allocated 2343 KB (sum 32950000)
Round 4: allocated 2343 KB (sum 32950000)
Round 5: allocated 2343 KB (sum 32950000)
Round 6: allocated 2343 KB (sum 32950000)

What this code does

  • With -XX:-DoEscapeAnalysis every round allocates 2,343 KB: 100,000 objects of 24 bytes each (on 64-bit HotSpot with default settings, a 12-byte header plus two 4-byte int fields, rounded up to a multiple of 8).
  • This is the work the young generation and the garbage collector would have to handle. Never turn escape analysis off in real use; the flag is here only to show what it saves.

For new Bill(price, 30) followed by b.total(), the compiled code just adds price and 30. No memory is taken from the heap, so the garbage collector has nothing to clean up later. This is controlled by -XX:+DoEscapeAnalysis and -XX:+EliminateAllocations, both on by default in HotSpot 17 and 21. People often say "the JVM puts the object on the stack". That is a simplified picture. HotSpot does not move objects to the stack; it removes the object and keeps only its fields.

Examples 1 to 3 and 6 measure allocation with com.sun.management.ThreadMXBean.getCurrentThreadAllocatedBytes(), a HotSpot-specific method available since Java 14.

Removing locks on objects no other thread can see

Lock elision means C2 removes synchronized locking on an object that does not escape the thread. A lock exists to stop two threads using an object at the same time; if only one thread can ever see the object, the lock protects nothing.

Example 4 · A local StringBuffer: locks nobody needs

LockElisionDemo.javaJava
public class LockElisionDemo {    // StringBuffer locks itself on every append. Here it never leaves the method,    // so no other thread can ever see it.    static int receiptLength(int orderId) {        StringBuffer sb = new StringBuffer();        sb.append("ORDER-").append(orderId).append("-PAID");        return sb.length();    }
    public static void main(String[] args) {        long fastest = Long.MAX_VALUE;        long total = 0;        for (int round = 1; round <= 15; round++) {            long start = System.nanoTime();            for (int i = 0; i < 1_000_000; i++) {                total += receiptLength(i % 1000);            }            fastest = Math.min(fastest, System.nanoTime() - start);        }        System.out.println("Fastest of 15 rounds: " + fastest / 1_000_000 + " ms");        System.out.println("Total length: " + total);    }}
Sample output
Fastest of 15 rounds: 30 ms
Total length: 208350000

What this code does

  • Each append call on StringBuffer is synchronized, so in the source every receipt takes and releases a lock three times, plus once more for length().
  • The StringBuffer never leaves receiptLength, so no other thread can see it. The fastest round is shown because single rounds on a busy laptop are noisy.

Example 5 · Lock elision on and off

Terminal
java LockElisionDemojava -XX:-EliminateLocks LockElisionDemo
Sample output
$ java LockElisionDemo
Fastest of 15 rounds: 28 ms
Total length: 208350000

$ java -XX:-EliminateLocks LockElisionDemo
Fastest of 15 rounds: 54 ms
Total length: 208350000

What this code does

  • With lock elision switched off, the fastest round went from 28 ms to 54 ms on this machine; repeated runs gave a similar gap. The total is the same, so the locks removed were truly useless.
  • In your own code the better fix is simply StringBuilder, which has no locks at all. Lock elision helps existing code; it is not a reason to choose StringBuffer.

The classic case is StringBuffer, whose methods are all synchronized. A StringBuffer that is created and used inside one method can have its locks removed. C2 can also merge several lock and unlock pairs on the same object into one, which is called lock coarsening. Lock elision is controlled by -XX:+EliminateLocks, on by default. It does not change behaviour: locks on objects that other threads can see are always kept.

Why escape analysis is an optimization, not a guarantee

Escape analysis can make code faster, but Java promises nothing about it. Your program must be correct and fast enough without it.

Example 6 · No JIT, no escape analysis

Terminal
java -Xint EscapeDemo
Sample output
$ java -Xint EscapeDemo
Round 1: allocated 2346 KB (sum 32950000)
Round 2: allocated 2343 KB (sum 32950000)
Round 3: allocated 2343 KB (sum 32950000)
Round 4: allocated 2343 KB (sum 32950000)
Round 5: allocated 2343 KB (sum 32950000)
Round 6: allocated 2343 KB (sum 32950000)

What this code does

  • With -Xint nothing is compiled, so every Bill is created on the heap in every round, exactly as the source says. The same is true for any cold code in a normal run.
  • That is the point of "an optimization, not a guarantee": the program is correct either way, and only C2-compiled hot code gets the benefit.
  • It happens only in C2-compiled code. Interpreted and C1 code always allocate, so cold code and code during warm-up still create every object.
  • It depends on inlining. If an object is passed to a method that is too big to inline, C2 must assume the object escapes.
  • It has limits. On HotSpot 17 and 21, arrays with more than 64 elements are not scalar replaced (EliminateAllocationArraySizeLimit), and very complex methods may give up on the analysis.
  • So write clear code, and use short-lived local objects freely, but never design around a specific allocation being removed. Measure when it matters.

Next step

Check your understanding

12 quick questions