没有引用对象时的Java垃圾回收

时间:2014-10-05 15:43:51

标签: java garbage-collection

例如,使用以下代码

class Dog {
    Dog parent;
    Dog (Dog parent) {
        this.parent = parent;
    }

    Dog makeDog (Dog dog) {
        return new Dog(new Dog(new Dog(dog)));
    }
}

public class test {
    public static void main(String[] args) {
        Dog dog = new Dog(null);
        dog = dog.makeDog(dog);
        Dog anotherDog = new Dog(dog);
        /*
         * many lines of code
         */
        if (anotherDog.parent.parent.parent.parent.parent == null) {
            System.out.println("null");
        }
    }
}

此程序是否保证打印为空?

我的大部分程序都在C中,这就是我构建链表,树,图等的方式。但是我真的不确定Java垃圾收集器将如何处理这样的代码,所以在真正的程序中,我选择将引用存储在其他地方,以便GC可以知道对象确实不是垃圾。

欢迎任何帮助。

1 个答案:

答案 0 :(得分:1)

只要可以通过GC根(线程堆栈或静态变量)的强引用链访问对象,就不会对其进行垃圾回收。与对象的路径有多复杂无关紧要。