Skip to content

Java Serialization

October 12, 2007
tags:

Java Serialization is used to persist Java objects. The persistence is achieved by writing the object state to an external system (it can be a file database etc). Once you have written an object, you can get the object back any time by reading the object back from that external source. This feature is mainly required when you are working in a distributed environment where your application is running in more than one JVM’s and you need to pass the objects from one JVM to another.

Serialization is achieved by using JAVA interface named “Serializable”. This is a marker interface (An interface that is just used to mark any class of being a particular type to let the JVM know that it is of that type. A marker interface does not contain any methods). We need to make any class implement the serializable interface (or inherit from a serializable class) if we want to persists the objects of that class. Its tells the JVM that the objects of this class can be serialized.

How to Serialize: After making any class implement the serializable interface, we need to write following few lines of code to actually serialize the objects of that class. Consider the following class that you want top serialize:

import java.io.*;
class Cat implements Serializable { }

public class SerializeCat

{

public static void main(String[] args) {

Cat c = new Cat();// serialization of the Cat object c, starts here
try

{

FileOutputStream fs = new FileOutputStream(“testSer.ser”);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();

}

catch (Exception e)

{

e.printStackTrace();

}

// deserialization of the Cat object c, starts here
try

{

FileInputStream fis = new FileInputStream(“testSer.ser”);
ObjectInputStream ois = new ObjectInputStream(fis);
c = (Cat) ois.readObject();
ois.close();

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

You can see that the serialization and deserialization requires calling the readObject() and writeObject() methods. These methods are present in the ObjectOutputStream and ObjectInputStream classes respectively. These methods actually perform the serialization of the object passed as the parameter. While serializing the object the current state of the object is saved. Here we are saving the state of the object by writing it to a file testSer.ser. Then we can restore or deserialize the same state of the object by using the ObjectInputStream’s readObject method. Note that here, since the readObejct() method returns the type Object so we need to cast the object to the required type explicitly.

Not everything might be serializable, make it Transient: If your class contains reference variables of other non serialzable classes, then while serializing the object of your class you would not be able to save the value or state of that reference variable of non serializable class. If you try saving you will get the following run time exception: java.io.NotSerializableException In this scenario, you have got following two choices:

1. To declare the reference variable transient by prefixing the variable declaration by keyword transient: In this case the state of the non-serializable reference will not be saved while saving the serializing the object of your class. Remember in this case, when the you deserialize the object of your class the value of the transient marked references of your class will be null as during deserialization the constructor of the class is never called.

2. To override the readObject and wrietObject methods of the ObjectInputStream and ObjectOutputStream classes respectively and save the state of the reference of the non-seriazable class.
In this case, you will have to call the defaultReadObject() and defaultWriteObject() methods in the readObeject() and writeObject() methods respectively and these calls should be the first line in the readObeject() and writeObject() methods. The methods should have the following signature only:

private void writeObject(ObjectOutputStream os)

{

// your code for saving the non serializable reference variables

}
private void readObject(ObjectInputStream os)

{

// your code to read the non serializable reference

}

After that you will have to specify how to save the state of the non serializable references of your class while saving the object of your class.

Advertisements
One Comment leave one →
  1. October 28, 2011 11:13 am

    You have mentioned that marker interface don’t have any methods… I have two questions for u..
    1. Externalizable is a marker interface having methods….it is the sub interface of serializable using which we can perform serialization,
    2. Runnable is a marker interface having run()
    so if u don’t agree with me than can u write a empty interface and provide some special behavior

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: