Sub topic 3
Reachability and GC roots: when an object becomes garbage
This chapter assumes you know basic Java syntax, the difference between an object and a reference to it, and how to run a program from the command line. It also assumes you have read the previous chapter on stack frames and the heap. Here you will learn the rule the JVM uses to decide that an object is garbage, and the places where that rule surprises people.
The rule: reachable means alive
Java has no free call. The JVM decides for you, using one rule: an object is live if the program can still reach it, and garbage if it cannot.
- A GC root is a reference the JVM treats as live without asking where it came from. Roots sit outside the heap, or are special heap objects.
- An object is reachable if some chain of references leads to it from a root. The chain can have any length.
- An object that no chain reaches is unreachable. The collector may reclaim its memory.
The collector does not ask whether you still intend to use an object. It only asks whether the program still can use it. A forgotten entry in a static map is reachable, so it stays. An object you are done with but that nothing references is gone at the next collection.
What counts as a GC root
The exact list is internal to the JVM. These are the root categories you meet in practice, and the ones heap-analysis tools report as "GC roots":
| Root | What it holds | Typical surprise |
|---|---|---|
| Local variables and parameters in active stack frames | References in every frame of every live thread, including the operand stack | An object stays alive while a method that holds it is still running |
| Static fields of loaded classes | Anything assigned to a `static` field | A static collection can keep its contents alive for the lifetime of the class |
| Live threads | The `Thread` object and its stack | A running thread keeps everything its stack references alive, even if it is idle |
| JNI references | Local and global handles held by native code | Native code that never releases a handle leaks the object |
| Loaded classes and class loaders | `Class` objects and the loader that defined them | A class loader that cannot be freed keeps all its classes and their statics |
| Monitors | Objects currently locked by a thread | A locked object cannot be collected |
| Internal JVM references | System class loader, preallocated exceptions, the string intern table, and similar | Not under your control |
Two of these deserve attention. Stack references are roots, so every call chain you are in keeps its arguments and locals alive. Static fields are roots, so they are the usual route for long-lived accidental references. The leaks chapter returns to this.
Tracing the object graph
Think of the heap as a directed graph. Objects are nodes. A reference field, array element, or local variable pointing to an object is an edge. The collector starts at the roots and follows edges, marking every object it visits. Anything left unmarked is garbage.
Object D has two incoming references, and removing one of them does not make it garbage. It stays live while any chain from a root remains. Objects E and F are the interesting case: each is referenced, but only by the other.
Why cycles are not a problem
A simple memory scheme called reference counting stores a counter in each object and frees it when the counter hits zero. E and F above would each have a count of one forever, so they would never be freed. HotSpot does not use reference counting. It uses tracing: the collector walks from the roots, so a group of objects that only reference each other, an island of isolation, is garbage as soon as nothing outside the island points in.
You do not need to break cycles by hand. Setting node.next = null to "help" the collector in a doubly linked list is unnecessary once the list itself is unreachable.
Observing reachability
The following program builds a two-object cycle and watches it through a WeakReference. A weak reference does not keep its target alive, so get() returns null once the target has been collected. The chapter on reference types covers these in detail. Here the reference only serves as a probe.
import java.lang.ref.WeakReference;
public class IslandDemo {
static class Node {
Node other;
final byte[] data = new byte[1024 * 1024]; // 1 MB so the object is easy to notice
}
static void requestGc() throws InterruptedException {
for (int i = 0; i < 3; i++) {
System.gc(); // a request, not a guarantee
Thread.sleep(100);
}
}
public static void main(String[] args) throws InterruptedException {
Node a = new Node();
Node b = new Node();
a.other = b;
b.other = a; // cycle: a <-> b
WeakReference<Node> probe = new WeakReference<>(a);
a = null; // local no longer points to the first node
requestGc();
System.out.println("After a = null: alive = " + (probe.get() != null));
b = null; // now no root reaches either node
requestGc();
System.out.println("After b = null: alive = " + (probe.get() != null));
}
}On a typical HotSpot run the output is:
After a = null: alive = true
After b = null: alive = falseThe first line is the point of the exercise. Clearing a did not free the first node, because the local variable b still reaches the second node, and the second node references the first. Only when both roots are gone does the island become garbage. The program asks the JVM to collect through System.gc(). The JVM is free to ignore the request, and some options such as -XX:+DisableExplicitGC do. So treat false on the last line as the expected result, not a promise.
Reachability is about liveness, not scope
A common belief is that a local variable keeps its object alive until the end of the block. The JVM specification does not say that. Once the JIT compiler (the part of the JVM that turns hot bytecode into machine code) sees that a local is never used again, that slot need not be treated as a root. An object can therefore become unreachable in the middle of a method, even while a variable that names it is still in scope.
This is usually harmless. It becomes a bug when code relies on an object staying alive for a side effect the compiler cannot see, such as a native handle that a cleanup action releases. The JDK offers java.lang.ref.Reference.reachabilityFence(obj) (since Java 9) for that case. Calling it at the end of the critical section keeps obj reachable up to that point.
The interpreter is more conservative than compiled code. A program may therefore behave differently when run in a short test than after warm-up. If an object's lifetime matters to correctness, make the dependency explicit instead of relying on observed behavior.
What reachability does not tell you
- Reachable does not mean needed. The collector keeps an object that a root still references, even if your program will never read it again. This is the definition of a Java memory leak.
- Unreachable does not mean freed immediately. Garbage stays in memory until a collection happens. Most collectors collect only part of the heap at a time, so it may wait longer than you expect.
- Nulling a reference is rarely useful. Setting a local variable to
nullbefore the method returns does nothing the return would not do. It matters only when a long-lived structure, such as a field in a cache, an array slot in your own stack implementation, or a static, holds a reference you no longer need.
Finalizers and resurrection
An object that overrides finalize() is treated specially. When it becomes unreachable, the JVM does not free it right away. It queues the object for a finalizer thread, and the object stays on the heap, reachable from the finalizer queue, until finalize() has run. If finalize() stores this in a static field, the object becomes reachable again, which is called resurrection. Finalization is deprecated since Java 9 and is unpredictable and slow. Prefer try-with-resources for deterministic cleanup, and java.lang.ref.Cleaner when you need a safety net.
Common mistakes
- Expecting an inner class to be independent. A non-static inner class instance holds a hidden reference to its enclosing instance. Passing the inner object to a long-lived registry keeps the outer object alive too. Make the class
staticunless it needs the outer instance. - Forgetting registrations. Event listeners, callbacks, and shutdown hooks stored in a long-lived collection stay reachable until you remove them.
- Leaving threads running. A thread blocked forever on a queue still has a stack, and everything on that stack stays live.
- Trusting
System.gc()in tests. A test that callsSystem.gc()and asserts an object disappeared can fail on a different collector or with a different flag. Use it for demonstrations, and loop with a timeout if you must check.
Exercise
A method builds a large HashMap, stores it in a static field named LAST_RESULT, and returns. A caller then drops all of its own references to the map. Is the map eligible for collection? What single change would make it eligible?
Show answer
No. The static field is a GC root, so the map stays reachable for as long as the class is loaded. Setting LAST_RESULT = null (or replacing it with a new value) removes the last chain from a root, and the old map becomes eligible at the next collection. Dropping the caller's references changed nothing, because the static field was an independent path.
Exercise
Two objects, P and Q, reference each other. A local variable in a running method references P. Then the method returns. Are P and Q garbage after it returns, assuming nothing else references either object? Why does the cycle not stop the collector?
Show answer
Yes, both are garbage. The local variable was the only root path, and the frame is gone after the return. HotSpot traces from roots instead of counting references, so the cycle between P and Q is an island that no root reaches. The references they hold to each other do not make them live.