Skip to lesson

Reachability and GC roots

The garbage collector never asks "is this object still useful?". It asks one question it can answer exactly: can the program still reach this object by following references from a GC root? Everything it cannot reach is garbage.

GC roots: where reachability starts

GC roots are starting points such as local variables, static fields and active threads; any object reachable from them stays alive, and the rest is garbage.

GC roots are references the collector treats as live without checking, because the running program can use them directly. Every search for live objects starts from them.

Three GC roots (a local variable, a static field, a live thread) lead by arrows to Order, Customer, Cart, Item and a Session: all reachable and kept. OldCart and OldItem point at each other but no root reaches them, so they are greyed out as garbage.

Example 1 · Three kinds of roots: a local, a static field and a live thread

GcRootsDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.concurrent.CountDownLatch;
class Session {    String user;
    Session(String user) {        this.user = user;    }}
public class GcRootsDemo {    static List<Session> activeSessions = new ArrayList<>();      // root: a static field
    static void login(String user) {        Session s = new Session(user);      // root while login() runs: a local variable        activeSessions.add(s);    }
    static void preview(String user) {        Session temp = new Session(user);        System.out.println("Previewing for " + temp.user);    }
    public static void main(String[] args) throws InterruptedException {        login("asha");        login("bala");        preview("guest");
        CountDownLatch done = new CountDownLatch(1);        new Thread(() -> {                  // nobody keeps a variable for this thread            Session courier = new Session("courier-7");            System.out.println("Tracking " + courier.user);            done.countDown();        }).start();        done.await();
        System.out.println("Sessions held by the static field: " + activeSessions.size());    }}
Output
Previewing for guest
Tracking courier-7
Sessions held by the static field: 2

What this code does

  • The sessions of asha and bala outlive login() because the static field activeSessions is a root and the list refers to them. The guest session was reachable only from preview()'s frame, so it is garbage once preview() returns.
  • No variable in main refers to the new thread, yet it is not garbage while it runs: a live thread is a root, and its courier session is reachable from that thread's own stack.

The main kinds (a simplified list for HotSpot):

  • Local variables and parameters in the stack frames of methods that are still running.
  • Static fields of loaded classes.
  • Live threads: a started thread that has not finished, and what its stack refers to.
  • JNI references: references held by native code (C or C++ called through the Java Native Interface). An object is not a root just because it is big or new. It is live only if a chain of references leads to it from one of these.
Simplified: once the JIT compiler has optimized a method, a local variable the method will never read again may stop counting as a root before the method returns. Do not write code that depends on this either way.

The object graph and reachable objects

The object graph is every object on the heap, with each reference drawn as an arrow from one object to another. An object is reachable when some path of arrows leads to it from a GC root.

Marking reachable objects from two roots

Step 1 of 5

main()staticOrderCustomerAddressCartItemOldCartOldItem
Two roots: the local variable order in main() and a static field. The collector will start only from these two.

Example 2 · A simplified model: mark everything reachable from the roots

ReachabilityDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Arrays;import java.util.Deque;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.TreeSet;
class Obj {    String name;    List<Obj> refs = new ArrayList<>();
    Obj(String name) {        this.name = name;    }
    void pointTo(Obj... others) {        refs.addAll(Arrays.asList(others));    }}
public class ReachabilityDemo {    static Set<String> reachableFrom(List<Obj> roots) {        Set<Obj> marked = new HashSet<>();        Deque<Obj> toVisit = new ArrayDeque<>(roots);        while (!toVisit.isEmpty()) {            Obj o = toVisit.pop();            if (marked.add(o)) {             // first visit: mark it, then follow its arrows                toVisit.addAll(o.refs);            }        }        Set<String> names = new TreeSet<>();        for (Obj o : marked) {            names.add(o.name);        }        return names;    }
    public static void main(String[] args) {        Obj order = new Obj("Order"), customer = new Obj("Customer"), address = new Obj("Address");        Obj cart = new Obj("Cart"), item = new Obj("Item");        Obj oldCart = new Obj("OldCart"), oldItem = new Obj("OldItem");        order.pointTo(customer);        customer.pointTo(address);        cart.pointTo(item);        oldCart.pointTo(oldItem);        oldItem.pointTo(oldCart, item);      // a cycle, plus an arrow into a live object
        List<Obj> all = List.of(order, customer, address, cart, item, oldCart, oldItem);        List<Obj> roots = List.of(order, cart);   // main()'s local and a static field
        Set<String> live = reachableFrom(roots);        Set<String> garbage = new TreeSet<>();        for (Obj o : all) {            if (!live.contains(o.name)) {                garbage.add(o.name);            }        }        System.out.println("Reachable: " + live);        System.out.println("Garbage:   " + garbage);    }}
Output
Reachable: [Address, Cart, Customer, Item, Order]
Garbage:   [OldCart, OldItem]

What this code does

  • This is a model of the heap, not the real collector: Obj objects stand for heap objects and refs for their references. reachableFrom does what the mark step does: start at the roots and follow every arrow once.
  • OldCart and OldItem refer to each other and to Item, yet both are garbage: no path from a root reaches them. The diagram above shows the same graph step by step.

The collector walks this graph from the roots and marks everything it touches. Whatever is left unmarked is garbage, however many arrows point out of it. An arrow from a garbage object to a live object does not keep anything alive; only arrows that start at a root count.

Predict the output

Which objects are garbage?

Read each snippet and pick the answer.

Round 1 of 3

Two orders, then one variable is pointed at the other.

Order a = new Order(1);
Order b = new Order(2);
a = b;

Cycles of objects are still collected

A cycle is a group of objects that refer to each other in a loop: A points to B and B points back to A.

Example 3 · Unreachable cycles are freed by a real JVM

CycleDemo.javaJava
import java.util.ArrayList;import java.util.List;
class Friend {    byte[] photo = new byte[1024];   // 1 KB so the memory is easy to see    Friend bestFriend;}
public class CycleDemo {    static long usedMb() {        Runtime rt = Runtime.getRuntime();        return (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024);    }
    public static void main(String[] args) {        List<Friend> pairs = new ArrayList<>();        for (int i = 0; i < 20_000; i++) {            Friend a = new Friend();            Friend b = new Friend();            a.bestFriend = b;            b.bestFriend = a;            // b -> a: a cycle            pairs.add(a);        }        System.gc();                     // demo only: settle the numbers        System.out.println("Used with 20000 pairs: " + usedMb() + " MB");
        pairs = null;        System.gc();        System.out.println("Used after dropping:   " + usedMb() + " MB");    }}
Sample output
Used with 20000 pairs: 41 MB
Used after dropping:   0 MB

What this code does

  • Every pair is a cycle: a and b point at each other. While pairs holds the a objects, all 40,000 objects are reachable and use about 40 MB.
  • After pairs = null the cycles are still there, but no root leads to them, so the collector frees them all. Exact numbers differ per machine (this run: HotSpot, Java 21, G1).

A doubly linked list, a parent with children that point back to it, and two "friends" in a social app all form cycles. Because the collector starts from roots, a cycle that no root reaches is simply never marked, so it is garbage like any other object. You do not need to break cycles by hand before you drop them.

Why Java does not use reference counting

Reference counting is another way to find garbage: every object keeps a count of how many references point to it, and it is freed the moment the count falls to 0.

Example 4 · Reference counting leaks a cycle (simulation)

RefCountDemo.javaJava
class Counted {    String name;    int count = 0;                       // how many references point here    Counted partner;
    Counted(String name) {        this.name = name;    }
    void setPartner(Counted other) {        partner = other;        other.count++;    }}
public class RefCountDemo {    public static void main(String[] args) {        Counted a = new Counted("A");        a.count++;        Counted b = new Counted("B");        b.count++;
        a.setPartner(b);        b.setPartner(a);                 // B -> A: a cycle        System.out.println("Counts with variables: A=" + a.count + ", B=" + b.count);
        Counted keepA = a, keepB = b;    // kept only so we can print the counts        a.count--;        a = null;        b.count--;        b = null;        System.out.println("Counts after dropping variables: A=" + keepA.count + ", B=" + keepB.count);        boolean freed = keepA.count == 0 && keepB.count == 0;        System.out.println("Reference counting frees them: " + freed);        System.out.println("Tracing from roots frees them: true (no root reaches A or B)");    }}
Output
Counts with variables: A=2, B=2
Counts after dropping variables: A=1, B=1
Reference counting frees them: false
Tracing from roots frees them: true (no root reaches A or B)

What this code does

  • This simulates a reference-counting runtime by hand: each new reference adds 1 and each dropped reference takes 1 away. (The real JVM keeps no such counts.)
  • Once the program's variables are gone, A and B still count 1 each, held up only by each other, so a counting runtime would never free them. Tracing from roots finds no path to them and frees both.

It has two problems that made the JVM's designers choose tracing from roots instead:

  • A cycle never reaches 0. A and B keep each other's count at 1 forever, even when the program cannot reach either, so the memory leaks.
  • Every assignment of a reference must update two counts. With many threads those updates must be safe across threads, which slows down ordinary code. Some languages do use it: CPython, the usual Python, counts references and runs a separate cycle detector for the first problem. HotSpot never counts references; its collectors trace from roots.

Interview answer: how GC decides what is garbage

A short, correct answer has four parts. Say them in this order.

  • The JVM uses reachability, not usage: an object is live if a chain of references leads to it from a GC root.
  • GC roots are locals in live stack frames, static fields, live threads and JNI references (plus a few JVM-internal ones).
  • The collector marks everything reachable from the roots; whatever is not marked is garbage, including cycles.
  • It does not count references, because counting cannot free cycles and slows every assignment.
A common follow-up is "Can Java leak memory then?". Yes: an object that is reachable but never used again, such as one left in a static list, is never collected.

Next step

Check your understanding

12 quick questions