Here is my java code:
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(pathName);
out = new ObjectOutputStream(fos);
out.writeObject(index);
out.close();
fos.close();
} catch (IOException e) {
LogManager.writeLogToFile(e.getMessage());
e.printStackTrace();
}
The index is an instance of inverted document index by myself. I have built the object index in memory, but when I pass it to the method writeObject(index), I get the error StackOverflowError. My question is: Why does this error happen after that I have built the object in the memory?
Suppose that the data structure of index is as follow:
class InvertedIndex{
private HashMap<String, PostList> index;
}
class PostList{
private int size;
private PostNode first;
}
class PostNode{
private String key;
private double weight;
private PostNode next;
}
To avoid recursive call, I overwrite the method writeObject and readObject of the PostList because it may be a very long list:
class PostList{
private void writeObject(ObjectOutputStream out) throws IOException{
PostNode temp = first;
while(temp != null){
out.writeObject(temp);
temp = temp.getNext();
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
in.defaultReadObject();
}
}
Then I get two questions:
- out.writeObject(temp); Because temp has a reference to the next node, when I write temp, recursive call will also happen. The same situation will continue even if I overwrite the writeObject method of PostNode with defaultWriteObject. Am I right? If so, what can I do to avoid this recursive call?
- How to overwrite the method readObject()?
It’s hard to know without seeing the class you’re serializing, but my guess would be that the object graph is too complex. Java’s default serialization mechanism works recursively through the object graph; that is, if you have object A with a reference to B, and you serialize A, it’ll have to walk to B and serialize that. If B then references C, and C references D, and so on, then it’s possible for the recursive algorithm to have to go so deep that it causes a stack overflow.
If that’s what’s causing your problem, you should write your own
readObjectandwriteObjectwhich avoid this recursive building, if possible.