Video in progress

When does an object become eligible for garbage collection?

When it can no longer be reached from the GC roots through any chain of strong references. It doesn't matter that the object itself holds references to other objects; what matters is whether there is a path to it from something alive.

📖 Answer

void demo() {
    User a = new User("Ali");   // object 1
    User b = new User("Vali");  // object 2
    a = b;                      // nobody points at object 1 anymore -> eligible
    b = null;                   // a still points at object 2 -> not eligible
}                               // the method ended -> object 2 is eligible too

The usual ways to become eligible: pointing the reference at another object or setting it to null, the method with the local variable ending, removing the object from a collection.

A cycle (circular reference) is not a problem: even with A -> B -> A, if there is no path to them from a root, both get collected. Java doesn't use reference counting.

"Eligible" does not mean "deleted immediately": the object can stay on the heap until the next GC cycle.