Search code examples
serializationrmi

Java Serialization with RMI


I'm working on a project using Java RMI. This is the class causing problem:

public class FSFile implements Serializable 
{
public static final int READ    = 0;
public static final int WRITE   = 1;

private int     flag;
private String  filename;

private transient BufferedWriter  writer;
private transient BufferedReader  reader;

...

private void writeObject(ObjectOutputStream stream) throws IOException
{
    stream.defaultWriteObject();
    stream.writeObject(writer);
    stream.writeObject(reader);    
}

private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException
{
    stream.defaultReadObject();
    writer      = (BufferedWriter) stream.readObject();
    reader      = (BufferedReader) stream.readObject();
}
}

Basically, I use RMI to send that FSFile object to another process locally (for now) and here's the error I get:

java.rmi.UnmarshalException: error unmarshalling return; nested exception is:                                                                      
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException;
java.io.BufferedReader

To be more precise, there's one class named FileService which use a function fetch() from a FileServer to get a FSFile in return. There is nothing special in the fetch() function, it just creates a FSFile and returns it. All communications between those classes are made via RMI.

How come I have an error like this ?


Solution

  • You can't serialize readers and writers. It makes no sense. It's like trying to send a telephone over a telephone line. If you want to send a file, send the file.

    And your code just calls writeObject on these objects as though they were Serializable. They aren't. Otherwise you could have made them non-transient and omitted the custom readObject and writeObject methods altogether. Just re-coding what the system would have done anyway doesn't change anything. It certainly doesn't make classes Serializable that aren't.