不再需要时,是否需要手动处理java树结构?(Do I need to manually dispose of a java tree structure when it is no longer n

编程入门 行业动态 更新时间:2024-10-28 11:18:42
不再需要时,是否需要手动处理java树结构?(Do I need to manually dispose of a java tree structure when it is no longer needed?)

我在我的应用程序中构建了许多对象树,其中每个节点都是典型的树节点(对父节点的引用和对子节点的引用列表)。 这些树是临时的,这意味着我可以在应用程序终止之前处理它们。

到目前为止,我总是向树节点类添加一个方法,该方法能够递归遍历树分支并“销毁它”(将父引用设置为null并清除子列表等)。

public void destroy() {
    for (Node node : children) {
        node.destroy();
    }
    parent = null;
    children.clear();
}
 

这对我来说总是有意义的,因为简单地将对存储在某处的树的根的引用置零是不够的 - 孩子们可能仍然有对它的引用,这意味着它将留在内存中并导致内存泄漏。 我是否正确地假设并提供这样的方法?

我怀疑自己的原因是我很少在API中看到提供树结构支持的这种方法(至少不直接在树节点接口中)。 处理此类案件的正确模式是什么?

I construct lots of object trees in my applications, where each node is your typical tree node (reference to parent and a list of references to children). These trees are temporary, meaning that I might dispose of them before application terminates.

So far I've always added a method to the tree node class which is able to recursively traverse a tree branch and "destroy it" (set parent reference to null and clear children list, etc.).

public void destroy() {
    for (Node node : children) {
        node.destroy();
    }
    parent = null;
    children.clear();
}
 

This always made sense to me, since simply null-ing a reference to the root of the tree which you have stored somewhere is not enough - children might still have a reference to it, meaning that it will stay in memory and cause a memory leak. Am I correct in assuming this and providing such a method?

The reason why I'm doubting myself is that I rarely see such methods in APIs which provide tree structure support (at least not directly in tree node interfaces). What is the proper pattern for dealing with such cases?

最满意答案

您不需要自己销毁或清洁物体。

你只需要确保活动对象没有对它们的引用( 现场声音清晰,但这是相当复杂的定义)。

请注意,即使不需要的对象中有课程参考,您也不需要关心它们,GC会处理这个问题。

有关:

在Java中将对象分配为null会影响垃圾回收吗?

一个类可以从类本身中取消吗?

是否真的有必要在JUnit拆解方法中使对象无效?

You do not need to destroy or clean objects yourself.

You just need to make sure that there are no references to them from live objects (live sounds clear but this is rather complex definition).

Note that even if there are curricular references in unneeded objects to themselves you do not need to care about them, GC will handle this.

Related:

Does assigning objects to null in Java impact garbage collection?

Can a class be nullified from within the class itself?

Is it really necessary to nullify objects in JUnit teardown methods?

更多推荐

本文发布于:2023-08-07 19:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465796.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:结构   dispose   manually   java   longer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!