简体   繁体   English

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

[英]Java garbage collection when there is no referencing object

For example with the following code, 例如,使用以下代码,

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");
        }
    }
}

Is this program guaranteed to print null? 该程序是否保证打印为空?

Most of my programs are in C, and this is the way I build linked lists, trees, graphs et cetera. 我的大多数程序都是用C语言编写的,这就是我建立链表,树,图等的方式。 But I am really not sure how the Java garbage collector will deal with such code, so in the real program, I chose to store the references elsewhere so the GC can know that the objects are indeed not garbage. 但是我真的不确定Java垃圾收集器将如何处理此类代码,因此在实际程序中,我选择将引用存储在其他位置,以便GC可以知道对象确实不是垃圾。

Any helps are welcome. 欢迎任何帮助。

As long as an object is reachable through a chain of strong references from a GC root (a thread stack, or a static variable), it will not be garbage collected. 只要通过GC根(线程堆栈或静态变量)中的一系列强引用可以访问对象,就不会对其进行垃圾回收。 It doesn't matter how convoluted the path to the object is. 到对象的路径有多复杂都没关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM