Java垃圾收集,将参考设置为null [英] Java Garbage collection, setting reference to null
问题描述
public class A {
A a;
public static void main(String args []){
A b = new A(); //创建新对象,obj1
ba = new A(); / /创建新对象,obj2
b = null;
//第8行
}
}
已达到,obj1符合GC要求。 obj2是否也符合GC的要求?
如果您想确定垃圾收集对象的资格,请尝试查看如果它可以从根集到达。在你的例子中,根集最初包含如果 obj1
args
(让我们忽略其他可能存在的 - 他们对你的例子无关紧要)。在第6行之前,由于 obj1
包含对<$ c $>的引用, args
。从 args
引用 obj1
或 obj2
,所以在第8行 obj1
和 obj2
都可以收藏。 public class A{
A a;
public static void main(String args[]){
A b = new A();//new object created, obj1
b.a = new A();//new object created, obj2
b = null;
//line 8
}
}
When line 8 is reached, obj1 is eligible for GC. Is obj2 also eligible for GC?
If you'd like to determine eligibility of an object for garbage collection, try to see if it is reachable from the root set. The root set are things like objects referenced from the call stack and global variables.
In your example, the root set initially consists if obj1
and args
(let's ignore any others that might exist - they don't matter for your example). Just before line 6, obj2
is clearly reachable from the root set, since obj1
contains a reference to obj2
. But after line 7, the only object in the root set is args
. There's no way either obj1
or obj2
is referenced from args
, so at line 8 both obj1
and obj2
are eligible for collection.
这篇关于Java垃圾收集,将参考设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!