predi
predi

Reputation: 5928

Do I need to manually dispose of a java tree structure when it is no longer needed?

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?

Upvotes: 3

Views: 1418

Answers (2)

OldCurmudgeon
OldCurmudgeon

Reputation: 65859

I considered this one recently and came to the conclusion that the answer is no - mostly.

If you have a normal Tree type structure using Nodes holding a reference to the data then the only way you could expose the structure (and therefore hold it from disposal) is to hand out your Nodes. If you do this then of course huge chunks of your tree could be referenced by another component.

Most of the time you will be handing out the data which does not itself have any reference to the rest of the nodes in the tree.

However, it is possible to mistakenly design your data structure so you expose the inner structure of your tree. For example, if you design your Map.Entry class to hold references to the trees structural components such as the node where the entry is then you will have a problem.

Remember that what the garbage collection process does is to consider everything as unreachable unless it is reachable. Just because you have a complex intertwined structure does not mean it is complex to discard.

Upvotes: 1

Vitaly
Vitaly

Reputation: 2800

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?

Upvotes: 4

Related Questions