I'm trying to write to and read from one file with ObjectInputStream and ObjectOutputStream, in two threads. Since I have to append to this file, so according to some online advise, I implement a class:
public class AppendableObjectOutputStream extends ObjectOutputStream {
public AppendableObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
protected void writeStreamHeader() throws IOException {
reset();
}
}
And the write logic is like:
synchronized (SDKLogger.failoverFile) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
if (failoverFile.exists()) {
fos = new FileOutputStream(SDKLogger.failoverFile, true);
oos = new AppendableObjectOutputStream(fos);
} else {
fos = new FileOutputStream(SDKLogger.failoverFile, true);
oos = new ObjectOutputStream(fos);
}
for (LogModel log : logs)
oos.writeObject(log);
Because I have synchronized on the global file only used for this purpose, not referenced anywhere else, I don't understand why I meet this exception always.
java.io.StreamCorruptedException: unexpected reset; recursion depth: 1
at java.io.ObjectInputStream.handleReset(Unknown Source)
at java.io.ObjectInputStream.access$600(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.refill(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.skipBlockData(Unknown Source)
at java.io.ObjectInputStream.skipCustomData(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
After searching the web, I find almost nothing on what this error is about and why one could come cross this error.
Thanks for your help in advance.