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();
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);
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
.tmpextension (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.serandobjectfile.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.