Search code examples
javagarbage-collectionjava-11

Will a parent object no more accessible from a GC root thread be elligible for Java GC even if one of its child is referenced by the root thread?


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.