假设我们有以下课程
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] 删除。
我来说两句