Sunday, October 28, 2012

Serialization

java. lang.Serializable is a marker interface. A class marked as Serializable is capable of being serialized by jvm provided mechanism.

Serialization mechanism serializes the state of the object including all the member variables except fields marked static or volatile.

During de-serialization volatile variables are assigned default values.

The default de/serialization mechanism can be overridden by providing two method implementations to the object

private void readObject(java.io.ObjectInputStream s){}
private void writeObject(java.io.ObjectOutputStream s){}

Please refer HashMap api for better understanding.

private void writeObject(java.io.ObjectOutputStream s){
   // below statement gives you the default behavior, skips volatile/static var
   s.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream s){
   // below statement gives you the default behavior, skips volatile/static var
   s.defaultReadObject();
}

A more customized implementation is in HashMap-
private void writeObject(java.io.ObjectOutputStream s){
   // below statement gives you the default behavior, skips volatile/static var
   s.defaultWriteObject();
   // write any other field
   s.writeInt(anIntegerProperty);
   s.writeObject(composedObject);
}
private void readObject(java.io.ObjectInputStream s){
   // below statement gives you the default behavior, skips volatile/static var
   s.defaultReadObject();
   //read any other field
   anIntegerProperty=s.readInt();
   composedObject=(ComposedObject)s.writeObject(); //typecast
}
A generated serialVersionUID for a serializable class is for JVM to check during deserialization that serialized content is compatible with object being constructed.
serialVersionUID can be same for compatible class version. This by default is written out to the stream during serialization.

No comments:

Post a Comment