Garbage collection

Mid-level Frequently asked 6 min

On this page

The question

How does the garbage collector decide what to collect?

30-second answer

It traces reachability, not age or usefulness. Starting from the GC roots, such as thread stacks and static fields, it follows references and marks every object it reaches. Anything unmarked can never be used again, so its memory can be reclaimed. That is why an unreachable cycle is freed, and why an unused object that is still referenced is not.

Understand it

Objects moving through the generations

Step by step

New objects start in Eden: A to E here. The young and old generation layout is the classic model; G1 and generational ZGC organize it as regions.

Step 1 of 5
View as text

A heap drawn as rows: Eden and the survivor spaces S0 and S1 make up the young generation, and the old generation sits below. Each object is a box with a letter and its age, the number of minor GCs it survived.

New objects start in Eden: A to E here. The young and old generation layout is the classic model; G1 and generational ZGC organize it as regions. The old generation already holds two long-lived objects, P and Q.

Eden fills, so a minor GC copies the live A, C and E to survivor space S0 at age 1. Dead B and D are simply freed. They stay behind in Eden, dashed and marked freed.

The next minor GC copies the live objects from Eden and S0 into S1, adding 1 to each age. C and the new G died, so they are freed. A and E are now age 2, and the new F lands in S1 at age 1.

A and E reached the tenuring threshold, 2 here, so the next minor GC promotes them to the old generation. HotSpot's default maximum is 15. F is copied back to S0 at age 2, and the dead H is freed from Eden.

When the old generation fills, a major GC marks every object reachable from the GC roots and frees the rest, here A and Q. It is rarer and slower. Arrows lead from the GC roots to P and E, which are marked and drawn as live.

A heap drawn as rows: Eden and the survivor spaces S0 and S1 make up the young generation, and the old generation sits below. Each object is a box with a letter and its age, the number of minor GCs it survived.

New objects start in Eden: A to E here. The young and old generation layout is the classic model; G1 and generational ZGC organize it as regions. The old generation already holds two long-lived objects, P and Q.

Eden fills, so a minor GC copies the live A, C and E to survivor space S0 at age 1. Dead B and D are simply freed. They stay behind in Eden, dashed and marked freed.

The next minor GC copies the live objects from Eden and S0 into S1, adding 1 to each age. C and the new G died, so they are freed. A and E are now age 2, and the new F lands in S1 at age 1.

A and E reached the tenuring threshold, 2 here, so the next minor GC promotes them to the old generation. HotSpot's default maximum is 15. F is copied back to S0 at age 2, and the dead H is freed from Eden.

When the old generation fills, a major GC marks every object reachable from the GC roots and frees the rest, here A and Q. It is rarer and slower. Arrows lead from the GC roots to P and E, which are marked and drawn as live.

Takeaway: Most objects die young, so the JVM collects the young generation often and cheaply, and promotes long-lived survivors to the old generation, which it collects rarely.

What the GC roots keep alive

Tap the parts

Select a part to see what it does.

Tap a part to see why the GC keeps it or frees it.

View as text

Two GC roots at the top, each with arrows to the objects it reaches, and two objects at the bottom that nothing reaches.

Thread stacks: the local variable order in main() is a root, with an arrow to an Order object, which has an arrow to a Customer object.

Static fields: the static field CACHE is a root, with an arrow to a HashMap.

Reachable object: Order and Customer are marked reachable, because a chain of references leads to each from a root.

Leaking cache: the HashMap has arrows to two Session objects marked unused. They are never used again, but they stay reachable, so the GC must keep them.

Unreachable cycle: Cart and Item, drawn dashed and marked unreachable, have arrows to each other but no arrow from a root, so the GC frees both.

Two GC roots at the top, each with arrows to the objects it reaches, and two objects at the bottom that nothing reaches.

Thread stacks: the local variable order in main() is a root, with an arrow to an Order object, which has an arrow to a Customer object.

Static fields: the static field CACHE is a root, with an arrow to a HashMap.

Reachable object: Order and Customer are marked reachable, because a chain of references leads to each from a root.

Leaking cache: the HashMap has arrows to two Session objects marked unused. They are never used again, but they stay reachable, so the GC must keep them.

Unreachable cycle: Cart and Item, drawn dashed and marked unreachable, have arrows to each other but no arrow from a root, so the GC frees both.

Takeaway: The GC frees only what no root can reach. A cycle does not save an object, but a forgotten reference, like a static cache entry, does.

Reachability from the GC rootsA thread stack reaches an Order, which reaches a Customer. A static field reaches a Map, which reaches a Session. All of them are live. A Cart and an Item reference each other, but no root reaches them, so they form an island that is collected.Unreachable: collecteditemscartRoot: thread stackOrderCustomerRoot: static fieldMapSessionCartItem
Reachability from the GC rootsA thread stack reaches an Order, which reaches a Customer. A static field reaches a Map, which reaches a Session. All of them are live. A Cart and an Item reference each other, but no root reaches them, so they form an island that is collected.Unreachable: collecteditemscartRoot: thread stackOrderCustomerRoot: static fieldMapSessionCartItem
Roots reach live objects, and an unreachable island is collected

In code

record Session(String user, byte[] data) {}

class Sessions {
    private static final Map<String, Session> CACHE = new HashMap<>();

    static void login(String user) {
        CACHE.put(user, new Session(user, new byte[1_000_000]));
    }
    static void logoutLeaky(String user) {
 Wrong         System.out.println(user + " logged out");    // the entry stays in CACHE
    }
    static void logout(String user) {
 Right         CACHE.remove(user);                          // no reference left
    }
}
A static cache keeps a logged-out session alive
class Node { Node next; }

Node a = new Node(), b = new Node();
a.next = b;
b.next = a;                                   // a cycle
var probe = new WeakReference<>(a);           // does not keep a alive
a = null;
b = null;                                     // no root reaches the cycle now
System.gc();                                  // a request, not a guarantee
System.out.println(probe.get());              // typically null
An unreachable cycle is collected
A static cache keeping old entries aliveThe static field CACHE references a HashMap, which references two old entries. They are never used again, but they stay reachable, so the GC keeps them.static CACHEHashMapold entryold entryGC keeps them
A static cache keeping old entries aliveThe static field CACHE references a HashMap, which references two old entries. They are never used again, but they stay reachable, so the GC keeps them.static CACHEHashMapold entryold entryGC keeps them
A static cache map keeps old entries alive
java -XX:+UseG1GC -Xms2g -Xmx2g -Xlog:gc*:file=gc.log -jar app.jar   # G1 (Garbage-First): the default since Java 9
java -XX:+UseZGC -Xmx16g -jar app.jar                                   # ZGC (Z Garbage Collector): sub-millisecond pauses on large heaps
Choose a collector and log what it does

Solve it

The heap grows for days, then OutOfMemoryError: find the leak

An order service runs fine after a deploy, but three days later it fails with “Java heap space”. Restarting fixes it for another three days. Find the cause and prove the fix.

  1. Tell a leak from a small heap. In the GC log, look at the heap right after each full or mixed collection. If that floor keeps rising under steady load, live objects accumulate: a leak.
  2. Capture the evidence. Start with -XX:+HeapDumpOnOutOfMemoryError, or take a dump from the running process with jcmd.
  3. Read the dump. Open it in Eclipse MAT (Memory Analyzer Tool) or VisualVM. The dominator tree shows a HashMap held by a static field, a GC root, with millions of entries that are never removed.
  4. Fix the owner. Bound the cache by size or age, or remove entries when they stop being needed.
  5. Prove it. Run the same load for hours: the floor after each collection now stays flat.
jcmd 4242 GC.heap_dump /tmp/orders.hprof                     # 4242 is the process id from `jcmd -l`
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp -jar orders.jar
Dump the heap of a running JVM, or on the first OutOfMemoryError
class LruCache<K, V> extends LinkedHashMap<K, V> {
    private final int max;
    LruCache(int max) { super(16, 0.75f, true); this.max = max; }   // true: access order
    @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > max; }
}

static final Map<String, Session> SESSIONS = Collections.synchronizedMap(new LruCache<>(10_000));
A size-bounded cache evicts the least recently used entry

How to answer

  • GC roots include local variables on thread stacks and the static fields of loaded classes.
  • An object is live if a chain of references leads to it from a root.
  • A cycle with no path from a root is garbage, because tracing never counts references.
  • Reachable does not mean needed: a forgotten reference keeps an object alive.
  • The JVM (Java Virtual Machine) chooses when to collect, so you cannot predict when an object is freed.

Common mistakes

  • Saying an object is freed when its reference count reaches zero.
  • Saying that setting a variable to null frees the object immediately.

Follow-up questions

What are the generations of the Java heap, and why do they exist?

Most objects die young, so the heap is split by age. New objects start in Eden, in the young generation. A minor GC copies the few survivors to a survivor space, which is cheap because dead objects are never copied. Objects that survive long enough are promoted to the old generation, which a major GC collects less often.

  • The classic young generation is Eden plus two survivor spaces, one of them empty between collections.
  • Each minor GC an object survives adds 1 to its age.
  • At the tenuring threshold, at most 15 by default in HotSpot, the object is promoted.
  • G1 and generational ZGC keep the generations but organize them as regions.

See it in the infographic: Objects moving through the generations

How do G1 and ZGC differ, and when would you choose each?

G1, the default since Java 9 on server-class machines, collects regions in stop-the-world pauses aimed at a target, 200 ms by default. ZGC does nearly all its work concurrently, so pauses typically stay under a millisecond even on large heaps, at the cost of extra CPU and memory. Start with G1; choose ZGC when latency matters most.

  • MaxGCPauseMillis defaults to 200 in G1, and it is a goal, not a guarantee.
  • ZGC relocates objects while the application keeps running.
  • Generational ZGC arrived in Java 21 behind -XX:+ZGenerational, became the default mode in 23 and the only mode in 24.
  • Select ZGC with -XX:+UseZGC, and measure on your own workload before switching.

See it in the infographic: Objects moving through the generations

Can a Java program leak memory even with garbage collection?

Yes. The GC frees only what is unreachable, so an object you no longer need but still reference stays. The classic case is a static collection that only grows, such as a cache with no eviction. The symptom is old generation use climbing after every collection, and eventually an OutOfMemoryError.

  • A Java memory leak is a reachable object that nothing will use again.
  • Common sources are static collections, listeners never removed and ThreadLocal values on pooled threads.
  • Fix it by removing entries or bounding the cache with eviction.
  • Diagnose it with a heap dump, following the path from the object to its GC root.
class GrowForever {
    private static final Map<Integer, byte[]> CACHE = new HashMap<>();

    public static void main(String[] args) {
        for (int i = 0; ; i++) CACHE.put(i, new byte[1_000_000]);
    }
}
// java -Xmx64m GrowForever: OutOfMemoryError: Java heap space

See it in the infographic: What the GC roots keep alive

Does System.gc() force a collection?

No, it is a request. The Javadoc promises only a best effort, and -XX:+DisableExplicitGC turns the call into a no-op. By default G1 answers it with a full, stop-the-world collection, which is a good reason not to call it in production code.

Why doesn't Java use reference counting?

Counting cannot free a cycle, because each object in it keeps the other's count above zero. It also adds a counter update to every reference assignment, which is costly when threads share objects. Tracing handles cycles and does its work during collections.

Check yourself

1. Two objects reference each other, and no GC root reaches either. What happens to them?
Show answers
  • A collection can free both: Correct. Tracing starts at the roots, so neither object is reached.
  • They stay until one reference is set to null: Incorrect. References between unreachable objects do not count.
  • The JVM throws an error at the next collection: Incorrect. A cycle is ordinary garbage, and nothing is thrown.
2. A survivor has reached the tenuring threshold. Where does the next minor GC put it, if it is still live?
Show answers
  • In the old generation: Correct. Reaching the threshold means the object is promoted.
  • Back in Eden: Incorrect. Eden receives only new objects, and collection leaves it empty.
  • In the other survivor space: Incorrect. That is what happens before the threshold, not at it.