Introduction To Serialization In Java

Introduction

In this article we discuss Serialization in Java.

Serialization

Serialization is a way to write the state of an object into a byte stream. The primary purpose of serialization is to write an object into a stream, so that it can be transported over a network easily and that object can be rebuilt again. The main use of serialization is in Hibernate, JPA, etcetera. The reverse operation of the serialization is called deserialization. The string class and all the wrapper classes implement the Serializable interface by default.

The following figure illustrate a lot about serialization in Java.

serialization.jpg

Example

Some examples of the use of serialization are:

  1. In the stock market
    When the users want a stock update urgently, for getting this, every time we need an update, so if we can serialize it and save it in a file. Then the user requests respond quickly, since the data is deserialized from the file and the information is provided to the user quickly.
  2. In the banking sector
    When the users withdraw/deposit money from the ATM, the details of the user account will be serialized and sent to the server where the details are deserialized and used the information to perform operations. Hence it will help in reducing the network calls.

The advantages are:

  • It is mainly used to transfer an object's state on the network.
  • The serialization stream can be easily compressed, supporting the needs of secure Java computing, authentication and encryption.
  • The classes that are serialized, since they are coherent and flexible so that they can support our application's object schema.
  • It is easy to use and can be customized.
  • There are simply too many critical technologies that depends upon serialization, like JavaBeans, RMI and EJB.

The disadvantages are:

  • Since serialization does not offer any transaction control mechanisms, it is not beneficial for use within those applications that need concurrent access without the use of additional APIs.
  • It should not be used with large-sized objects, since it offers significant overhead. Since large objects need substantial amounts of memory in our application.
  • The Serializable interface does not provide fine control over object access.

Reasons why we use serialization are:

  • to send data to a remote computer using such client/server Java technologies since RMI or socket programming.
  • to exchange data between applets and servlets.
  • to persist data for future use.
  • to "flatten" an object into an array of bytes in memory.
  • to send objects between the servers in a cluster.

How serialization works

Step 1

When we want to serialize an object, the class must implement the marker interface Serializable.

Step 2

This just gives information to the compiler that this Java class should be serialized.

Step 3

We can remove properties that should not be serialized.

Step 4

Now, we write the object into a stream. The Application Programming Interface (API) is used to do the serialization process and save the file with conformance.

Step 5

De-serialization is the reverse process, used to get the object back from the file to its original form.

Here protocol means, the understanding between the serializing person and the de-serializing person. What will be the contents of the file containing the serialized object? This serves as a guideline to de-serialize. Have a look at the following sample and how its serialized file looks.

Serializable Interface

It is a marker interface (that has no body).

Example

In this example we create an interface using the Serializable interface, this interface contains a student's record like his name and his id.

import java.io.Serializable;
public class Interface implements Serializable
 
{
   
int sid;
   
String sname;
   
public Interface (int sid, String sname)
`     
{
       
this.sid=sid;
       
this.sname=sname;
      }
  }

Some commonly used constructors are:

  1. public ObjectOutputStream (OutputStream out) throws IOException {}
    used to create an ObjectOutputStream to write the specified OutputStream.

Some commonly used pubilc methods are:

  1. final void writeObject(Object p) throws IOException {}
    serializes the object and returns it to an output stream.
  2. final Object readObject() throws IOException
    retrieves the next object and deserializes it.
  3. void flush() throws IOException {}
    flushes the current output stream.

Example

In this example we serialize a class that contains a student's record, like his id and name and this will be stored in a p.txt file.

import java.io.Serializable;
public class Interface implements Serializable
  {
    int sid;
    String name;
    public Interface(int sid, String name)
 
     {
        this.sid = sid;
        this.name = name;
      }
  }

import java.io.*;
class SerializationEx1
  {
    public static void main(String args[])throws Exception
      {
        Interface st =new Interface(211,"ravi");
        FileOutputStream fout=new FileOutputStream("p.txt");
        ObjectOutputStream oout=new ObjectOutputStream(fout);
        oout.writeObject(st);
        oout.flush();
        System.out.println("you have successfully saved your record");
      }
  }

Output

pic-1.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all