user1786193
user1786193

Reputation: 19

ObjectInputStream.readObject causing EOFException

I'm programming a simple client-server application, where the server opens a thread, that watches a directory for file-creations. These files are serialized objects. The thread should deserialize them, read the data and create a new object to send it to the client. so in general it works pretty well, but sometimes I get:

java.io.EOFException at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2571) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369) at ServerSend.start(ServerSend.java:58) at ServerSend.run(ServerSend.java:25) at java.lang.Thread.run(Thread.java:722)

but why is this happening? and why only sometimes... One part of the program where I read the Object:

FileInputStream fileStream = new FileInputStream(dirpath+"/"+t);
ObjectInputStream ois = new ObjectInputStream(fileStream);
Object toSend = ois.readObject();

Source code on pastebin

Some other programms create these objects, my StreamReader wants to read:

FileOutputStream fileStream = new FileOutputStream(filepath_to_where_listening);
            ObjectOutputStream oos = new ObjectOutputStream(fileStream);
            oos.writeObject(mmout);

Upvotes: 0

Views: 2236

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533520

The can be caused by two considitions

  • the file wasn't closed properly resulting in the end of the file being truncated. If the file is discarded, the GC can close the file for you, but this behaviour is unreliable.
  • the ObjectOutputStream writeXxxx while the ObjectInputStream readYyyy where Xxxx is not Yyyy. e.g. writeObject and readInt will result in this error.

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272287

Is that file being created atomically ? Or is it possible that you're reading the file whilst its being created ?

You could create the file with a .tmp extension (say) and then remove the extension once the file is complete. It depends on the filesystem in use, but I'd expect this to be atomic for most (all?) Unix/Linux filesystems.

Alternatively your writing process could write the file, and then write a corresponding flag file, that indicates that it's finished writing the serialised object (e.g. objectfile.ser and objectfile.ser.done)

Another solution (strongly non-deterministic) is to watch for the file, and then wait a specified amount of time before reading it, to allow it to complete its creation.

Upvotes: 1

Related Questions