即使无法从GC根线程访问父对象,对于Java GC,即使根线程引用了它的子对象之一,对于Java GC也无法识别该父对象?

吉普87c

假设我们有以下课程

public class Parent {
  
  public Child child;

  public Parent(Child child) {
    this.child = child;
  }
}

public class Child {

  public String someField;
}

我们的主要代码如下

Parent parent = new Parent(new Child());
Child child = parent.child;
parent = null;
// then do other stuff

将父级设置为null后,即使主根线程直接引用了其内部字段/子级之一,父级是否也可用于垃圾回收?

曼努蒂

是的,它将符合GC的条件,因为Child它没有对的引用Parent,而Parent在将其变量设置为null时也没有引用该对象。注意:这可以通过调用System.gc()(出于测试目的)并覆盖Parent和Child中的finalize()方法来进行演示。当JVM确定已为GC准备就绪时,将在对象上调用该方法。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章