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?