简体   繁体   中英

Java OptionalDataException when only serializing objects (no primitive data types anywhere)

I'm dealing with a strange OptionalDataException that I can't figure out.

I have objects coming in, which are saved to disk by a class that write them by decorating an OutputObjectStream and calling its writeUnshared method. Periodically, every 10000 objects, it calls flush and reset . Finally, it closes the stream.

This way, I create a small number of files that only contain serialized objects.

Here's the thing. After all those files are written, I take a pair and try to mergesort them. At this point, size of the files hasn't changed (as expected).

To do this, I start by opening two streams and calling readObject on each one.

However, this call to readObject (the first one on each stream) throws OptionalDataException , everytime with eof = false, length = 4 , which as I understand indicates that I'm reading a primitive data type, or something else is happening that I'm not getting.

OK, need to share this.

I had created a wrapper for an ObjectOutputStream, that as I said, counted the amount of serialized objects in order to call reset periodically.

The problem was in the constructor of that class, which basically was:

class CustomObjectOutputStream extends ObjectOutputStream {

    private int flushBoundary;

    CustomObjectOutputStream(ObjectOutputStream oos, int flushLimit){
               super(oos);
               ...
     }
   //other methods
}

Now, a closer look to the javadoc page says that

Creates an ObjectOutputStream that writes to the specified OutputStream. This constructor writes the serialization stream header to the underlying stream; callers may wish to flush the stream immediately to ensure that constructors for receiving ObjectInputStreams will not block when reading the header.

Meaning that there was "some extra stuff" at the beggining of the file. I changed the super() call to the default one, and the OptionalDataExceptions dissapeared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM