Saturday 22 September 2012

Java Serialization


What is Serialization in Java?
Java Serialization is the process of writing the states of an object into a byte stream which includes the object's data as well as information about the object's type and type of data stored in the object.

This process is JVM independent, that means an object which is serialized on one platform can be deserialized on an entirely different platform.

The main purpose of Java serialization is to write the states of the object in a stream of bytes that can be transported through a network and that object then can be rebuild again.

How to make a Java class Serializable?
A class must implement a marker interface Serializable in order to have a capabilities of serializing its objects. This interface just informs the JVM that this class can be serialized.
If you don't want any of the class's property not to be serialized, mark it as transient.

A sample program to create a serializable class:

import java.io.*;
import java.io.Serializable;

class Employee implements Serializable {
private static final long serialVersionUID = 1L;
public String empName;
public String address;
public transient int ssn; // this will not be serialized,it will be having
// default value when deserializing it from disk
public int age;

public Employee(String name, String addr, int number, int age){
this.empName=name;
this.address=addr;
this.ssn=number;
this.age= age;
}
}

public class SerializeDemo{
public static void main(String[] args){
Employee e1 = new Employee("Piyush", "Pune",1001, 32);
FileOutputStream fileOutput=null;
try{
fileOutput = new FileOutputStream("D:/STUDY/java/workspace/OUTPUTS/employee.ser");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOutput);
objectOut.writeObject(e1);
System.out.println("Employee object is serialized in employee.ser");
objectOut.close();
fileOutput.close();
}
catch(IOException fne){
fne.printStackTrace();
}
try{
FileInputStream fileInput = new FileInputStream("D:/STUDY/java/workspace/OUTPUTS/employee.ser");
ObjectInputStream objectInput = new ObjectInputStream(fileInput);
Employee e =(Employee) objectInput.readObject();
System.out.println("Employee is reConstructed from disk");
System.out.println(e.address);
System.out.println(e.empName);
System.out.println(e.ssn); // it may have default value depending on
// how its declared in serialized class.
System.out.println(e.age);
objectInput.close();
fileInput.close();
}
catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}



What is the difference between Serializable and Externalizable interface in Java?
Externalizable provides us writeExternal() and readExternal() method which gives us flexibility to control java serialization mechanism instead of relying on Java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically.

What is serialVersionUID? What would happen if you don't define this?

Whenever you implements serializable interface in your class to serialize it, by default JVM inserts ( if you don’t define your own versionID) a unique ID which is called serialVersionUID. JVM uses this id to serialize and deserialize an object. JVM Creates this UID depending on the structure of your class, like the methods used in the class, objects in the class any interface implemented etc.
It is always better to define your own serialVersionUID in your calss.If you are using the default definition of serialVersionUID, and later on if you are going to alter your class, java will create a different UID as the structure of the class is changed and serialize objects with this new UID. Problem occurs when you try to deserialize an old object of this class, at that time the UIDs will not be matched and you will get “NotSerializableException”.

While serializing you want some of the members not to serialize? How do you achieve it?
mark those members as transient.

What will happen if one of the members in the class doesn't implement Serializable interface?
One of the easy question about Serialization process in Java. If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException’ will be thrown at runtime

from the above example, create a class person which doesnt extends serializable interface and also modify Employee class:

class Person{
public String name;

public Person(String name){
this.name= name;
}
}
class Employee implements Serializable {
       Person per;
       public Employee(String name, String addr, int number, int age, Person p){
this.empName=name;
this.address=addr;
this.ssn=number;
this.age= age;
this.per = p; //non serializable class's object
}
}

while serializing it will throw"NotSerializableException"


If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization? --- 

At the time of deserialization, the constructor of the parent class will be called, which will override the value of the instance variable of super class, that it has at the time of serialization.