Pages

Java Serialization

Java Serialization is the process of converting the data into stream of bytes and storing into the files or database. Serialization is mainly used in Hibernate, RMI, JPA, EJB and JMS Technologies. The reverse operation of serialization is called Deserialization where byte-stream is converted into an object. The Serialization and Deserialization process is platform-independent, it means you can serialize an object in a platform and deserialize in different platform.


What is SerialVersionID ?

When ever an object is serialized the object is stamped with a version id number for the object class.


Why Java Serialization ?

Serialization is a mechanism for storing an object’s states into a persistent storage like disk files, databases, or sending object’s states over the network. The process of retrieval and construction of objects from disk files, databases and network is called de-serialization.

Examples of using Serialization :
1. Storing data in an Object Oriented way to files on Disk, Example : Storing a list of Employee Objects.
2. Saving program’s states on Disk, Example : Saving State of a Game like Temple Run.
3. Sending data over the network in form objects, Example : Sending messages as objects in Chat Application like Facebook, Whatsapp.

How does Serialization Work in Java ?

Java provides Serialization Interface in java.io Package and an object is eligible for serialization if and only if its class implements the Serializable Interface. Serializable is a marker interface that contains no methods, Serialization tell the Java Virtual Machine (JVM) that the objects of this class is ready for being written to and read from a persistent storage or over the network. The JVM takes care of the process of writing and reading serializable objects by default.

Two Methods are using while Serialization and Deserialization Functionalities as shown below :

ObjectOutputStream.writeObject(Object) : Writes a serializable object to the output stream. writeObject(Object) method throws NotSerializableException if some object to be serialized does not implement the Serializable interface.

ObjectInputStream.readObject() : reads, constructs and returns an object from the input stream. readObject() method throws ClassNotFoundException, if class of a serialized object cannot be found.

writeObject(Object) and readObject() Methods throw InvalidClassException, if something is wrong with a class used by serialization. Throw IOException if an Input and Output error occurs. Both NotSerializableException and InvalidClassException are sub classes of IOException.


What is Externalization in Java ?

The Java Virtual Machine (JVM) is totally responsible for the process of writing and reading objects while Serialization Process. This is useful in most cases, as the programmers do not have to care about the underlying details of the serialization process. The default serialization does not protect sensitive information like passwords and credentials.

Java provides Externalization Interfaces in java.io Package and sub interface of Serializable that means Externalizable extends Serializable, So if any class implements Externalizable Interface and override it’s writeExternal() and readExternal() methods then first preference is given to these methods over default serialization mechanism provided by JVM.

Programmer want to control the process of reading and writing objects during the Serialization and Deserialization process, have the object’s class implemented the Externalizable Interface. Then you implement your own code to write object’s states in the writeExternal() method and read object’s states in the readExternal() method.

The Externalizable Interface have two methods as shown below :

writeExternal(ObjectOutput out) : The object implements this method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.

readExternal(ObjectInput in) : The object implements this method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.


Differences between Externalizable and Serializable


Serializable Interface Externalizable Interface
Serializable Interface is a marker interface that means does not contain any method. Externalizable Interface contains two methods writeExternal() and readExternal() which implementing classes should override.
Default serialization does not call any class constructor. A public no-arg constructor is required while using Externalizable interface.
Mostly, default serialization is easy to implement, but has higher performance cost. Serialization done using Externalizable, add more responsibility to programmer but often result in better performance.
It’s hard to analyze and modify class structure because any change may break the serialization. It’s more easy to analyze and modify class structure because of complete control over serialization logic.
Serializable interface pass the responsibility of serialization to JVM and it’s default algorithm. Externalizable provides control of serialization logic to programmer – to write custom logic.


Serialization Example

package com.jaladhi;

import java.io.*;
public class Demo implements java.io.Serializable {
      public int a;
      public String b;
      public Demo(int a, String b) {
            this.a = a;
            this.b = b;
      }
}
public class Test {
      public static void main(String[] args) {
            Demo object = new Demo(1, "Jaladhi Soft Technology");
            String filename = "file.ser";
            // Serialization
            try {
                  FileOutputStream file = new FileOutputStream(filename);
                  ObjectOutputStream out = new ObjectOutputStream(file);
                  out.writeObject(object);
                  out.close();
                  file.close();
                  System.out.println("Object has been serialized");
            } catch(IOException ex) {
                  System.out.println("IOException is caught");
            }
            Demo object1 = null;
            // Deserialization
            try {
                  FileInputStream file = new FileInputStream(filename);
                  ObjectInputStream in = new ObjectInputStream(file);
                  object1 = (Demo)in.readObject();
                  in.close();
                  file.close();
                  System.out.println("Object has been deserialized ");
                  System.out.println("a = " + object1.a);
                  System.out.println("b = " + object1.b);
            } catch(IOException ex) {
                  System.out.println("IOException is caught");
            } catch(ClassNotFoundException ex) {
                  System.out.println("ClassNotFoundException is caught");
            }
      }
}

Output :

Object has been serialized
Object has been deserialized
a = 1
b = Jaladhi Soft Technology

Deserialization Example

package com.jaladhi;

import java.io.*;
public class Emp implements Serializable {
      private static final long serialversionUID = 129348938L;
      transient int a;
      static int b;
      String name;
      int age;
      public Emp(String name, int age, int a, int b) {
            this.name = name;
            this.age = age;
            this.a = a;
            this.b = b;
      }
}
public class SerialExample {
      public static void printdata(Emp object1) {
            System.out.println("name = " + object1.name);
            System.out.println("age = " + object1.age);
            System.out.println("a = " + object1.a);
            System.out.println("b = " + object1.b);
      }
      public static void main(String[] args) {
            Emp object = new Emp("ab", 20, 2, 1000);
            String filename = "shubham.txt";
            // Serialization
            try {
                  FileOutputStream file = new FileOutputStream (filename);
                  ObjectOutputStream out = new ObjectOutputStream (file);
                  out.writeObject(object);
                  out.close();
                  file.close();
                  System.out.println("Object has been serialized \n" + "Data before Deserialization.");
                  printdata(object);
                  object.b = 2000;
            } catch (IOException ex) {
                  System.out.println("IOException is caught");
            }
            object = null;
            // Deserialization
            try {
                  FileInputStream file = new FileInputStream (filename);
                  ObjectInputStream in = new ObjectInputStream (file);
                  object = (Emp)in.readObject();
                  in.close();
                  file.close();
                  System.out.println("Object has been deserialized \n" + "Data after Deserialization.");
                  printdata(object);
            } catch (IOException ex) {
                  System.out.println("IOException is caught");
            } catch (ClassNotFoundException ex) {
                  System.out.println("ClassNotFoundException" + " is caught");
            }
      }
}

Output :

Object has been serialized
Data before Deserialization.
name = ab
age = 20
a = 2
b = 1000
Object has been deserialized
Data after Deserialization.
name = ab
age = 20
a = 0
b = 2000