Memory management basics

Every Java thread has a stack for method calls and local variables, and all threads share a heap for objects. The garbage collector frees heap objects that nothing references any more, so a memory leak in Java is simply a reference you forgot about. This page makes the stack and heap visible, measures how deep the stack goes and how big objects really are, shows the JIT removing allocations, and reproduces two leaks.

Contents

Stack, heap and references

Each Java thread has a stack of frames, one per method call in progress. A frame holds the method's parameters and local variables and is discarded when the method returns, so stack memory needs no garbage collection. All threads share one heap, where every object and array lives, from the moment new runs until the garbage collector finds that nothing can reach the object any more.

A local variable of a primitive type, such as int count, holds the value itself in the frame. A local variable of a reference type, such as Point p, holds only a reference, a pointer to an object on the heap. On a 64-bit JVM with a heap under 32 GB, references are stored as 32-bit compressed oops (ordinary object pointers), which keeps objects small.

Where things live
ThingLives inFreed
Local primitive (int x)The thread's stack frameWhen the method returns
Local reference (Point p)The reference in the frame, the object on the heapReference: on return; object: by the GC when unreachable
Instance fieldInside its object on the heapWith the object
Static fieldWith its class's data, reachable as long as the class is loadedOnly if the class is unloaded
Array elementsInside the array object on the heapWith the array
A temporary object the JIT proves cannot escapePossibly nowhere: its fields become registers (scalar replacement)Not applicable

The programs ran on JDK 21, 64-bit, with default settings unless noted. For how the collector itself works, see garbage collection and JVM memory.

Java passes references by value

A method receives copies of its arguments. For a reference, that copy points to the same object, which leads to the most common confusion about Java parameters. The program passes a Point, a String and an array to methods that try to change them.

Java
public class StackVsHeap {

    static class Point {
        int x;
        int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    // p is a copy of the reference, stored in this method's stack frame
    static void move(Point p, int dx) {
        p.x += dx;                        // changes the shared heap object
        p = new Point(0, 0);              // changes only the local copy of the reference
        p.x = 999;
    }

    static void rename(String n) {
        n = n.toUpperCase();
    }

    static void bump(int[] values) {
        values[0] = 100;
    }

    public static void main(String[] args) {
        int local = 5;                    // a primitive local: lives in the stack frame
        Point point = new Point(1, 2);    // the reference is on the stack, the object on the heap
        move(point, 10);
        System.out.println("local = " + local + ", point.x = " + point.x + " (not 999)");


        // Strings are immutable, so "changing" one inside a method only rebinds the copy
        String name = "ann";
        rename(name);
        System.out.println("name = " + name + " (rename assigned a new String to its copy)");

        // Arrays are objects: the method receives a copy of the reference to the same array
        int[] counts = {1, 2, 3};
        bump(counts);
        System.out.println("counts[0] = " + counts[0] + " (the array itself was changed)");
    }
}

Output:

Output
local = 5, point.x = 11 (not 999)
name = ann (rename assigned a new String to its copy)
counts[0] = 100 (the array itself was changed)
  • move changed p.x through its copy of the reference, so the caller's point went from 1 to 11. It then pointed its copy at a new Point and set that one to 999; the caller never saw it, because only the method's own frame changed.
  • rename made its parameter refer to a new, upper-case string. Strings are immutable, so the caller's "ann" could not change, and the caller's variable still refers to it.
  • bump changed an element of the array the caller passed, and the caller saw 100: arrays are objects on the heap, shared through the copied reference.
  • So Java is always pass-by-value; the value of a reference variable just happens to be a pointer. A method cannot make the caller's variable refer to a different object, but it can change the object both of them refer to.

How deep the stack goes

Each thread's stack has a fixed maximum size, set for new threads with -Xss (default 1 MB on 64-bit Linux). A method that calls itself without end adds frames until the stack is full. The program runs the same recursion in three child JVMs with different stack sizes. It uses -Xint, interpreter only, because compiled frames are smaller than interpreted ones and the JIT compiles at unpredictable moments, which makes the depth vary between normal runs.

Java
import java.nio.file.Path;

public class StackDepth {

    public static class Recurse {
        static int depth;

        static void down() {
            depth++;
            down();
        }

        public static void main(String[] args) {
            try {
                down();
            } catch (StackOverflowError e) {
                System.out.println(depth);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
        // -Xint keeps every frame interpreted, so the depth is the same on every run
        for (String xss : new String[] {"-Xss256k", "-Xss1m", "-Xss4m"}) {
            Process p = new ProcessBuilder(java, "-Xint", xss, "-cp",
                    System.getProperty("java.class.path"), "StackDepth$Recurse")
                    .redirectErrorStream(true).start();
            p.getOutputStream().close();
            String depth = new String(p.getInputStream().readAllBytes()).lines()
                    .filter(l -> !l.startsWith("Picked up")).findFirst().orElse("?");
            p.waitFor();
            System.out.printf("%-9s StackOverflowError after %,d calls%n", xss,
                    Integer.parseInt(depth.trim()));
        }
    }
}

Output:

Output
-Xss256k  StackOverflowError after 1,795 calls
-Xss1m    StackOverflowError after 10,732 calls
-Xss4m    StackOverflowError after 46,479 calls
  • With 1 MB the recursion reached 10,732 calls, so each interpreted frame of this tiny method used about 100 bytes. Quadrupling the stack to 4 MB gave over four times as many calls; with 256 KB it was far fewer than a quarter, because the JVM reserves guard pages at the end of every stack to detect the overflow safely.
  • In normal runs, with the JIT active, the same program reached several times deeper, and the number changed from run to run.
  • Deep recursion over user-controlled data, such as parsing nested JSON, should be rewritten as a loop with an explicit stack, or run on a thread created with a larger stack size through the Thread constructor or Thread.Builder.stackSize. Raising -Xss for the whole JVM costs memory in every thread.

How big objects really are

Every object starts with a header: a mark word used for locking, hashing and GC, and a compressed pointer to its class, 12 bytes in total. Arrays add a 4-byte length. Objects are then padded to a multiple of 8 bytes. The program measures sizes with the JVM's own per-thread allocation counter by creating a million objects of each kind.

Java
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntFunction;

public class ObjectSizes {

    static final com.sun.management.ThreadMXBean THREADS =
            (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();

    static class Empty { }

    static class OneInt {
        int a;
    }

    static class TwoLongs {
        long a;
        long b;
    }

    static class ThreeRefs {
        Object a;
        Object b;
        Object c;
    }

    // Average bytes allocated per object, measured by the JVM's own per-thread counter
    static long bytesPer(IntFunction<Object> factory) {
        int n = 1000000;
        Object[] keep = new Object[n];                      // allocated before measuring
        long tid = Thread.currentThread().threadId();
        long before = THREADS.getThreadAllocatedBytes(tid);
        for (int i = 0; i < n; i++) {
            keep[i] = factory.apply(i);
        }
        long after = THREADS.getThreadAllocatedBytes(tid);
        return Math.round((after - before) / (double) n);
    }

    public static void main(String[] args) {
        System.out.println("bytes per object (64-bit JVM, compressed pointers):");
        System.out.printf("  new Object()           %3d%n", bytesPer(i -> new Object()));
        System.out.printf("  empty class            %3d%n", bytesPer(i -> new Empty()));
        System.out.printf("  class with one int     %3d%n", bytesPer(i -> new OneInt()));
        System.out.printf("  class with two longs   %3d%n", bytesPer(i -> new TwoLongs()));
        System.out.printf("  class with three refs  %3d%n", bytesPer(i -> new ThreeRefs()));
        System.out.printf("  Integer (value 1000+)  %3d%n", bytesPer(i -> 1000 + (i & 1023)));
        System.out.printf("  new int[0]             %3d%n", bytesPer(i -> new int[0]));
        System.out.printf("  new int[10]            %3d%n", bytesPer(i -> new int[10]));
        System.out.printf("  new String(char[8])    %3d  (includes the char[8] argument)%n",
                bytesPer(i -> new String(new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'})));

        // A million numbers: primitive array versus boxed list
        long tid = Thread.currentThread().threadId();
        long t0 = THREADS.getThreadAllocatedBytes(tid);
        int[] prims = new int[1000000];
        long t1 = THREADS.getThreadAllocatedBytes(tid);
        List<Integer> boxed = new ArrayList<>(1000000);
        for (int i = 0; i < 1000000; i++) {
            boxed.add(i + 1000);
        }
        long t2 = THREADS.getThreadAllocatedBytes(tid);
        System.out.printf("1,000,000 ints: int[] %.1f MB, ArrayList<Integer> %.1f MB (%d, %d)%n",
                (t1 - t0) / 1e6, (t2 - t1) / 1e6, prims.length, boxed.size());
    }
}

Output (64-bit JVM, compressed pointers):

Output
bytes per object (64-bit JVM, compressed pointers):
  new Object()            16
  empty class             16
  class with one int      16
  class with two longs    32
  class with three refs   24
  Integer (value 1000+)   16
  new int[0]              16
  new int[10]             56
  new String(char[8])     80  (includes the char[8] argument)
1,000,000 ints: int[] 4.0 MB, ArrayList<Integer> 20.0 MB (1000000, 1000000)
  • An empty object takes 16 bytes: the 12-byte header plus 4 bytes of padding. One int fits into that padding, so it is still 16. Two longs need 12 + 16 = 28, padded to 32. Three references take 12 + 3 × 4 = 24.
  • An Integer is a full object of 16 bytes for 4 bytes of data. new int[0] is 16 bytes (header plus length), and new int[10] is 16 + 40 = 56.
  • The string line counts both the temporary char[8] argument and the new string: a 24-byte String object plus a 24-byte byte[], since compact strings (Java 9) store Latin-1 text one byte per character.
  • A million ints took 4 MB as an int[] and 20 MB as an ArrayList<Integer>: 4 MB for the list's array of references plus 16 MB of Integer objects. Boxed collections of numbers cost about five times the memory, and their elements are scattered across the heap.

Java 24 added compact object headers as an experimental option (JEP 450), and in Java 25 -XX:+UseCompactObjectHeaders works without unlocking experimental options. It shrinks the header to 8 bytes, which makes many of these objects 8 bytes smaller. Java 27 turns it on by default (JEP 534).

Allocations the JIT removes: escape analysis

When the JIT compiler can prove that an object never leaves a method, neither returned, stored in a field nor passed to code it cannot see, it can skip the allocation and keep the fields in registers. This is scalar replacement, based on escape analysis. A walk that adds a small Point to a position ten million times is measured with the analysis on (the default) and off.

Java
import java.lang.management.ManagementFactory;

public class EscapeAnalysis {

    record Point(double x, double y) {
        Point plus(Point o) {
            return new Point(x + o.x, y + o.y);
        }
    }

    // Creates two Points per iteration, but none of them escapes the method
    static double walk(int steps) {
        Point pos = new Point(0, 0);
        for (int i = 0; i < steps; i++) {
            pos = pos.plus(new Point(1, 0.5));
        }
        return pos.x() + pos.y();
    }

    public static void main(String[] args) {
        var threads = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
        long tid = Thread.currentThread().threadId();
        for (int i = 0; i < 20; i++) {
            walk(100000);                                   // let the JIT compile walk()
        }
        long before = threads.getThreadAllocatedBytes(tid);
        double result = walk(10000000);
        long allocated = threads.getThreadAllocatedBytes(tid) - before;
        System.out.printf("EscapeAnalysis %s: result %.1f, heap allocated by 10,000,000 steps:"
                + " %s%n", System.getProperty("ea.mode"), result,
                allocated < 1000000 ? "under 1 MB" : "about " + allocated / 1000000 + " MB");
    }
}

Output with default settings:

Output
EscapeAnalysis on: result 15000000.0, heap allocated by 10,000,000 steps: about 320 MB

Output with -XX:-DoEscapeAnalysis:

Output
EscapeAnalysis off: result 15000000.0, heap allocated by 10,000,000 steps: about 640 MB
  • Without escape analysis, every step allocated two 32-byte Points: 10 million × 64 bytes = 640 MB.
  • With it, allocation halved to 320 MB. The temporary new Point(1, 0.5) passed to plus was eliminated. The pos objects were still allocated: each new pos replaces the previous one across loop iterations, and HotSpot's C2 compiler in Java 21 cannot scalar-replace an object that is merged from several allocation sites like that.
  • Escape analysis is an optimization you can benefit from but not rely on. Small, short-lived objects, such as records used as return values, often cost nothing; but a slightly different code shape can bring the allocation back.

Two classic leak patterns

The collector frees only unreachable objects. Anything still referenced, even by mistake, stays. The program builds the two most common leaks: a static collection that only grows, and a map key that changes after insertion.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LeakPatterns {

    // Leak 1: a static collection that only grows
    static final List<byte[]> AUDIT = new ArrayList<>();

    // Leak 2: a key whose hashCode changes after insertion can never be removed
    static class Session {
        String user;

        Session(String user) {
            this.user = user;
        }

        @Override
        public int hashCode() {
            return user.hashCode();
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Session s && s.user.equals(user);
        }
    }

    static long usedMb() {
        Runtime rt = Runtime.getRuntime();
        System.gc();
        return (rt.totalMemory() - rt.freeMemory()) >> 20;
    }

    public static void main(String[] args) {
        long base = usedMb();
        for (int i = 0; i < 500; i++) {
            AUDIT.add(new byte[100000]);           // "temporary" data kept forever: 50 MB
        }
        System.out.println("static list holds about " + Math.round((usedMb() - base) / 10.0) * 10
                + " MB after GC");
        AUDIT.clear();
        System.out.println("after clear: about " + Math.round((usedMb() - base) / 10.0) * 10
                + " MB");

        Map<Session, byte[]> cache = new HashMap<>();
        Session s = new Session("ann");
        cache.put(s, new byte[1024]);
        s.user = "bob";                              // hashCode changes while it is a key
        cache.remove(s);
        cache.remove(new Session("ann"));
        System.out.println("entries left after both removes: " + cache.size());
    }
}

Output:

Output
static list holds about 50 MB after GC
after clear: about 0 MB
entries left after both removes: 1
  • After a collection, the static list still held about 50 MB: a static field is a root, so everything it refers to is reachable for as long as the class is loaded. Caches, registries and "audit" lists without a size limit or removal are the textbook leak. Clearing the list released the memory.
  • The Session key's hash code depends on user, which changed after the entry was added. remove(s) looked in the bucket for "bob" and remove(new Session("ann")) found the right bucket but the stored key no longer equals "ann", so neither removal worked and 1 entry stayed forever. Fields used in hashCode and equals must not change while the object is a key; immutable keys such as records avoid the problem. See equals and hashCode.

Other common leaks are listeners that are registered but never removed, ThreadLocal values on pooled threads (see ThreadLocal), and class loaders kept alive by a single reference. Finding them is a job for a heap dump; see memory leaks.

Memory rules of thumb

Habits that keep memory use predictable
SituationDo
Large collections of numbersUse primitive arrays or primitive streams, not boxed collections
Caches and registriesBound their size, or use weak keys where appropriate (reference types)
Map keys and set elementsMake them immutable
Deep or unbounded recursionUse a loop with an explicit stack, or a thread with a larger stack
Short-lived helper objectsWrite clear code first; escape analysis often removes them
Measuring object sizesAllocation counters or Instrumentation.getObjectSize, not guesses
Suspected leakTake a heap dump and look for the path to a GC root