1

One class in my program has one LinkedList which usually contains a large number of elements. When serializing this class, one Stackoverflow error occurred. I understand this is due to the recursive manner of serializing links in a list. So I want to override the writeObject of this list to an iterative way, but I don't know how to do this.

  • possible duplicate https://stackoverflow.com/questions/12963445/serialization-readobject-writeobject-overrides – Ori Marko Jun 04 '17 at 10:32
  • 1
    An ArrayList serializes without recursion. I suppose the satck overflow happens due to the structure of the elements of your list. – laune Jun 04 '17 at 10:47
  • I assume you have your own list implementation as LinkedList doesn't have this issue. I suggest you look at the source for LinkedList to see how they do it. (Or use the builtin LinkedList) I am surprised that someone understands how to write customise serialization, but not how to iterate over a linked list without recursion. – Peter Lawrey Jun 04 '17 at 11:05

1 Answers1

1

If one of the elements is your Object MyObject which have reference to MyObject for example:

public class MyObject implements Serializable {
  private MyObject nextObject;
  public void setNextObject(MyObject nextObject) {
    this.nextObject = nextObject;
...
}

if each MyObject link to next/previous MyObject the serialization process will: Start to write first MyObject and before it finish writing the first it will start to write second MyObject and so on until last object.

This structure can cause serialization stackoverflow exception with large number of elements.

Solution is to save unique Id for next object as: private int nextObjectId;

Ori Marko
  • 56,308
  • 23
  • 131
  • 233