Issue
Let's say we have the following classes
public class Parent {
public Child child;
public Parent(Child child) {
this.child = child;
}
}
public class Child {
public String someField;
}
And we have the following code in our main
Parent parent = new Parent(new Child());
Child child = parent.child;
parent = null;
// then do other stuff
Will the parent be elligible for garbage collection after setting it to null even if one of its internal field / child is directly referenced by the main root thread ?
Solution
Yes it will be eligible for GC, because Child
has no reference to Parent
, leaving no references to the Parent
object when its variable is set to null. Note: this can be demoed by invoking System.gc() (for testing purposes), and overriding the finalize() method in Parent and Child. The method will be invoked on the object when the JVM determines that it's ready for GC.
Answered By - M A
Answer Checked By - David Marino (JavaFixing Volunteer)