Java垃圾收集,将参考设置为null [英] Java Garbage collection, setting reference to null

查看:111
本文介绍了Java垃圾收集,将参考设置为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

code>和 args (让我们忽略其他可能存在的 - 他们对你的例子无关紧要)。在第6行之前,由于 obj1 包含对<$ c $>的引用, obj2 显然可以从根集中访问C> OBJ2 。但是在第7行之后,根集中的唯一对象是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆