Erick Alves Erick Alves - 2 months ago 7
Java Question

Is an Object eligible for GC even if its instance variable is references to another variable?

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)?

Answer

Initially, you have

stack --> x --> list

x is thus reachable from the stack.

Then you have

stack --> x --> list
     \          /
      \--------/

x is still reachable from the stack, and list is reachable, too, through x, and through the local variable on the stack

Then you set x to null, so you have

 stack      x --> list
     \          /
      \--------/

And you thus see that there is now way to reach x anymore from the stack. The fact that there is a path from x to the list is irrelevant. So the VM is allowed to collect x:

 stack           list
     \          /
      \--------/