在obj = null"之后是否有资格进行垃圾回收? [英] Is object eligible for garbage collection after "obj = null"?
问题描述
我知道 System.gc()
不能保证引起GC,但理论上在下面的代码中,对象 obj code>有资格进行垃圾回收?
public class Demo {
public static void main(String [] args)抛出异常{
SomeClass obj = new SomeClass();
ArrayList list = new ArrayList();
list.add(obj);
obj = null;
System.gc();
}
}
class SomeClass {
protected void finalize(){
System.out.println(Called);
}
}
调用 System.gc()
您创建的 SomeClass
实例的位置是 not 有资格进行垃圾回收,因为它仍然被列表
对象引用,即它仍然是可到达的。。
$但是,只要此方法返回 list
超出范围,那么 list
)。
只需设置参考 obj
为null本身不会使对象引用符合垃圾回收的条件。一个对象只有在符合可视对象图形的 no 引用时才符合条件。
I know System.gc()
is not guaranteed to cause GC, but theoretically, in the following code, will the object obj
be eligible for garbage collection?
public class Demo {
public static void main(String[] args) throws Exception {
SomeClass obj = new SomeClass();
ArrayList list = new ArrayList();
list.add(obj);
obj = null;
System.gc();
}
}
class SomeClass {
protected void finalize() {
System.out.println("Called");
}
}
At the point where you call System.gc()
the SomeClass
instance you created is not eligible for garbage collection because it is still referred to by the list
object, i.e. it is still reachable.
However, as soon as this method returns list
goes out of scope, so obj
will then become eligible for garbage collection (as will list
).
Simply setting the reference obj
to null does not, by itself, make the object referred to eligible for garbage collection. An object is only eligible if there are no references to it from the graph of visible objects.
这篇关于在obj = null"之后是否有资格进行垃圾回收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!