How do I serialise a graph in Java without getting StackOverflowException?

Posted by Tim Cooper on Stack Overflow See other posts from Stack Overflow or by Tim Cooper
Published on 2010-04-07T07:08:10Z Indexed on 2010/04/07 7:13 UTC
Read the original article Hit count: 226

Filed under:
|
|

I have a graph structure in java, ("graph" as in "edges and nodes") and I'm attempting to serialise it. However, I get "StackOverflowException", despite significantly increasing the JVM stack size. I did some googling, and apparently this is a well known limitation of java serialisation: that it doesn't work for deeply nested object graphs such as long linked lists - it uses a stack record for each link in the chain, and it doesn't do anything clever such as a breadth-first traversal, and therefore you very quickly get a stack overflow.

The recommended solution is to customise the serialisation code by overriding readObject() and writeObject(), however this seems a little complex to me.

(It may or may not be relevant, but I'm storing a bunch of fields on each edge in the graph so I have a class JuNode which contains a member ArrayList<JuEdge> links;, i.e. there are 2 classes involved, rather than plain object references from one node to another. It shouldn't matter for the purposes of the question).

My question is threefold:
(a) why don't the implementors of Java rectify this limitation or are they already working on it? (I can't believe I'm the first person to ever want to serialise a graph in java)
(b) is there a better way? Is there some drop-in alternative to the default serialisation classes that does it in a cleverer way?
(c) if my best option is to get my hands dirty with low-level code, does someone have an example of graph serialisation java source-code that can use to learn how to do it?

© Stack Overflow or respective owner

Related posts about java

Related posts about serialization