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?
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
obj1andargs(let’s ignore any others that might exist – they don’t matter for your example). Just before line 6,obj2is clearly reachable from the root set, sinceobj1contains a reference toobj2. But after line 7, the only object in the root set isargs. There’s no way eitherobj1orobj2is referenced fromargs, so at line 8 bothobj1andobj2are eligible for collection.