When does an object become eligible for garbage collection in Java?
An object becomes eligible when no live thread can reach it through any chain of references. The JVM then frees its memory at a time of its own choosing.
Explain it simply
Think of a hall booking nobody holds a slip for. If no one can find the hall, the venue staff may clear it. They decide when to do the cleaning; you cannot force it.
Java does not use reference counting. It starts from roots (local variables, static fields, active threads) and follows references. Anything not reached is garbage, even if two dead objects point to each other.
Example
Student s = new Student("Asha"); // reachable through s
s = null; // now unreachable: eligible
Student a = new Student("A");
Student b = new Student("B");
a.friend = b;
b.friend = a;
a = null;
b = null; // circular, but still unreachable: eligibleSystem.gc() is only a hint. finalize() is deprecated; use try-with-resources or AutoCloseable to release files and connections.
What to say in the interview
"An object is eligible once it is no longer reachable from GC roots such as live thread stacks and static fields. Circular references do not keep it alive. I cannot force collection, so I release external resources explicitly instead of relying on finalizers."
Common mistakes
- Believing setting a variable to null deletes the object immediately.
- Expecting memory leaks to be impossible in Java. A static list that keeps growing still leaks.