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.
Asked
Active
Viewed 149 times
1
-
possible duplicate https://stackoverflow.com/questions/12963445/serialization-readobject-writeobject-overrides – Ori Marko Jun 04 '17 at 10:32
-
1An 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 Answers
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
-
May I further ask, how would you rewrite the writeObject function in this situation? – user3025839 Jun 04 '17 at 13:43
-
I had similar issue I switch to save in MyObject int nextObjectId. Just save a key for next object and not the whole object – Ori Marko Jun 04 '17 at 13:44