The way around this problem is to implement an explicit non-recursive object-serialize method and object-deserialize constructor for affected classes. The general algorithm is fairly simple:
- Iterate non-recursively over the nodes in the datastructure. For each node, temporarily null out its pointers and serialize the node normally. The SerializeOutputStream will remember the objects and will not dump them out again if the same object is serialized later.
- If the number of nodes was not known in advance, serialize out a sentinel value to delimit the end of the nodes.
- Iterate over the nodes again in the same order and serialize the fields in order.
The following example demonstrates this problem for a simple linked list data structure. Note that in the linked list case the algorithm only requires a single
iteration because the next pointer is always just the next element to be serialized. To see the stack overflow, comment out the object-serialize and object-deserialize members.
Note how I used the class version as an optimization to avoid serializing an extra null for each instance.
Fixing this for my tree classes was a little bit more complicated but the principle is the same. You can see my changes here.