I'm studing for the Java Certification 1Z0-803 and I hava a doubt about garbage collection:
import java.util.*;
class X {
List<String> list = new ArrayList<>();
}
public class TestGC {
// Is an Object eligible for GC even if its instance variable is references to another variable
public static void main(String[] args){
X x = new X(); // 1
List<String> list = x.list;
x = null; // 2, Is X object reference eligible for garbage collection here?
list.add("a");
list.add("b");
list.add("c");
for(String item : list) {
System.out.println(item);
}
list = null;// 3, Or X object reference eligible for garbage collection here, after list is set to null
}
}
x
is referencing the object X
created at the position 1.
This class X
has a instance variable of the type List
.
If I referenced the instance variable list
on x of the type X
in a local variable list
and then set x
to null, the object referenced for x
will be eligible for GC in this line (position 2) or because I'm referencing an instance variable of this object, this object only be eligible for GC when its instance variable does not have anything reference to it (position 3)?