Saturday, May 3, 2014

Object Serialization and How it is done?

We encounter many questions on Object serialization and in this blog i am writing my experience of goldmann sachhs interview when i gave it. They asked me questions on serialization in a series of steps.

Firstly they asked have u heard of Serialization mechanism in java? Then they asked if yes, how it is done. That is if i have to serialize an employee object write a program that would serialize the employee object and store it in a file and then deserialize it.

We all know that Object Serialization refers  to a mechanism of  saving the state of an object when passing it over a network. Now the question arises is when we serialize an object we all know we have to implement a Serializable interface in our Class and give a unique serialVersion UID for that class. Now the next question arises is if i have to save the state of an object in a file, then write a code that would do that and what if i wont give this unique serialVersionUID in my class.





Object Serialization is a mechanism of saving the state of an obejct when passing over a network to a byte stream. We can later restore these objects by using the process of deserialization. Serialization is also needed to implement Remote Method Invocation (RMI). RMI allows a java object on one machine to invoke a method of a java obejct on q different machine. An obejct may be supplied to that remote method. Serializable is a marker interface i.e there is no method defined in that interface. 


After this, he asked me to write a code that will serialize an object and then deseriaize it.

package com.javaLearningHub;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class MyClass implements Serializable{
String s;
int i;
double d;
public MyClass(String s,int i, double d){
this.s=s;
this.i=i;
this.d=d;
}
public String toString(){
return "s="+s+";i="+i+";d="+d;
}
}
public class SerializableExample {

public static void main(String[] args) {
//Object Serialization
try(ObjectOutputStream objOStream=new ObjectOutputStream(new FileOutputStream("serial"))){
MyClass object1=new MyClass("Hello",2,4.5e10);
System.out.println("Object1 which is serialized is :"+object1);
objOStream.writeObject(object1);
}
catch(IOException e){
System.out.println("Exception caught during serialiation: "+e);
}
//Object deserialization
try(ObjectInputStream objIStream=new ObjectInputStream(new FileInputStream("serial"))){
MyClass object2=(MyClass)objIStream.readObject();
System.out.println("Object 2 deserialized is: "+object2);
}
catch(Exception e){
System.out.println("Exception caught during deserialization "+e);
} 
}


}


Here, we are serializing an object by using ObjectOutputStream class which extends the ObjectStream class and implements the ObjectOutput interface. This class is responsible for writing objects to a stream. This class accepts an input parameter as an OutputStream class object to which serialized objects will be written.
While deserializing an object we are using ObjectInputStreamClass which extends the input Stream class and implements the ObjectInput Interface. It is responsible for reading objects from  a stream.

Now the main questions arises is when we are serializing myClass above we are not creating a unique static final Long SerialVersionUID and that can cause a problem during deserialization. 

The concept lies here is the serialization mechanism associates a unique version number called a serialVersionUID which is used during deserialization to verify that both sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has  a different serial version UID than that of the corresponding senders class, then deserialzation will result in InvalidClassException.
Serializable class can declare its own serialVersionUID explicitly by declaring a static final Long field names as serialVersionUID.



static final long serialVersionUID=42L; (For example)

If  a serializable class does not explicitly declare  a serial version UID,the the serialization runTime will calculate  a default serialVersionUID for that class based on various aspects of the class. However it is recommended that all serializable classes explicitly declare serialVersionUID's to gurantee a consistent serialVersionUID values across different java compiler implementations and to avoid InvalidClassCast expection during deserialization.

Hope things are clear, in case of any queries, feel free to post in comments.

No comments:

Post a Comment