1

I am working on a tree structure, where events have to be able to travel down to the root element. At the same time I use the visitor pattern to serialize this tree. The visitor is supplied with a reference to the root, and travels up the tree.

Therefore I need to use some kind of circular referencing (for events the child needs to know its parent, for visitors the parent needs to know all children).

class TreeNode { List<TreeNode> children; TreeNode parent; ... } 

I now want to break up these circular references. Freeing up the root node, should automatically free the whole rest of the tree.

I've been experimenting with weak references for the parent field. I got null pointer exceptions, because java freed up the parent field which was afterwards accessed by an event.

How to solve this?

2
  • 3
    Are you sure that you actually have a Problem? Java will be happy to cycle collect if no one is holding a reference to any element of the tree. Your data structure as is means that any TreeNode will make the whole tree stay in memory, but why do you consider that a Problem? Commented Mar 28, 2014 at 16:22
  • By convention, only the leaves and the root is referenced from outside. Basically I haven't experienced any memory issues till now. I simply wasn't aware that java is able to clean up those "memory islands" that keep referencing themselves. Commented Mar 28, 2014 at 16:28

1 Answer 1

4

The Java garbage collection is smart enough not to be fooled by circular references. As soon as there are no Strong References to the tree then the entire tree complete with circular references will all be garbage collected.

All you need to do is ensure that there are no references from outside the Tree to anywhere inside the Tree.

If an event was accessing the parent field then that suggests something still had a reference. You will need to clean that up (whether you remove the circular references or not).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.