Java › Garbage Collection
What does it mean for an object to be 'eligible for garbage collection' in terms of reachability from GC roots?
BeginnerAnswer
An object becomes eligible for garbage collection once it's no longer reachable through any chain of references starting from a GC root -- GC roots include active local variables and parameters on any thread's current stack frames, static fields, and JNI references -- if you trace every reference chain starting from these roots and a particular object is never encountered, it's unreachable and therefore eligible for collection, regardless of how many objects might still reference EACH OTHER in an isolated island with no path back to any GC root (a scenario reference counting alone would fail to collect, but reachability-based tracing correctly identifies as garbage).
public void example() {
Object a = new Object();
Object b = new Object();
a = null; // the original object 'a' pointed to now has NO reachable reference -- eligible for GC
b = null; // same for the object 'b' pointed to
// Both original objects are now unreachable from any GC root and will eventually be collected
}Real-world example A circular reference between two objects (each holding a reference to the other) that are both otherwise unreachable from any GC root is still correctly identified as garbage by Java's reachability-based collector, unlike a simpler reference-counting scheme (used by some other languages) which would incorrectly consider each object still 'referenced' by the other and fail to collect this circular island.