gpt4 book ai didi

java - 当子对象引用父对象时对象销毁

转载 作者:行者123 更新时间:2023-12-01 12:28:51 25 4
gpt4 key购买 nike

代码示例:

public class Parent{
public void someMethod(){
//start of some sort of loop
Child child = new Child(this);

//do something
//replaces reference from old child to new child
child = new Child(this);
//repeats loop
}
}

public class Child{
Parent parent;
public Child(Parent parent){
this.parent = parent;
}
}

根据我对对象生命周期的理解,如果一个对象不再被引用,那么它将有资格进行GC,就像当子引用更改为引用新的第二个子对象时一样。
< br/>但是,如果每个子对象都有一个对创建它的对象的引用,就像上面一样,那么一旦它不再被其父对象引用,在这种情况下它是否有资格进行 gc?

如果不是,我该如何写它呢?

最佳答案

根据this answer :

Java's GC considers objects "garbage" if they aren't reachable through a chain starting at a garbage collection root, so these objects will be collected. Even though objects may point to each other to form a cycle, they're still garbage if they're cut off from the root.

因此,您无需为此循环引用案例执行任何特殊操作。

关于java - 当子对象引用父对象时对象销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26113146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com