public class A{
A a;
public static void main(String args[]){
A b = new A();//new object created, obj1
b.a = new A();//new object created, obj2
b = null;
//line 8
}
}
When line 8 is reached, obj1 is eligible for GC. Is obj2 also eligible for GC?
is useless, because one line later you already reach the end of scope of b. None of the 2 objects are reachable after leaving the scope where they are defined, since their reference wasn't put somewhere else, by a method call or as paramter in a constructor call, or as backreference from something else, which was published somewhere else.
If you'd like to determine eligibility of an object for garbage collection, try to see if it is reachable from the root set. The root set are things like objects referenced from the call stack and global variables.
In your example, the root set initially consists if
obj1
andargs
(let's ignore any others that might exist - they don't matter for your example). Just before line 6,obj2
is clearly reachable from the root set, sinceobj1
contains a reference toobj2
. But after line 7, the only object in the root set isargs
. There's no way eitherobj1
orobj2
is referenced fromargs
, so at line 8 bothobj1
andobj2
are eligible for collection.The only reference you created to
obj2
was withinobj1
(b.a = new A();
). As soon as you lost your reference toobj1
(b = null;
) you also lost your reference toobj2
, so yes, it is eligible for GC.Yes and here is an example showing GC in action:
Output: