Java Serialization

0
593

In this post I am going to cover the basic concept of Serialization. This is a must to understand topic if you need to work further on EJBs, Hibernate, JTA etc.

Java Serialization

is a way provided to convert java objects into streams i.e. sequence of bytes/data to be stored at a desired target (file, ds, network, process or any other system) and could easily be restored back into the original object whenever needed. Example of few cases when you might need to serialize your class(es) could be – writing data into a flat file for as is use, traversing data between environments in case of distributed system(there could be ways to achieve it but behind the scene it is serialization which will facilitate it) etc.

There are few classes which are exception for serialization and hence can not be serialized. One example on top of my mind is Thread class. So in case the class you are trying to serialize has any attribute of type ‘Thread’, then you explicitly need to inform the system not to serialize that. It means that there are ways through which you can explicitly exclude an attribute from getting serialized. The way is keyword – ‘transient‘. We can discuss about the keyword in detail later on. As a one liner – this keyword does not allow the marked attribute to get serialized when you try to serialize an object.

For an object to be serialized, it must be an instance of a class that implements either the

java.io.Serializable which does not contain any method (just a marker interface)

or

java.io.Externalizable interface which extends java.io.Serializable

When an object is serialized, the highest serializable class in its derivation hierarchy is located and serialized first. The hierarchy is walked with each subclass being serialized in turn.

I/O HIERARCHY

Following diagram can be helpful to understand file handling i.e serialization to/from file. I have tried to put some popular example in the diagram.
java_io

I/O OBJECT STREAM
ObjectOutputStream is the primary output stream class which implements ‘ObjectOutput’ interface for serializing the objects.

ObjectInputStream is the primary input stream class which implements ‘ObjectInput’ interface for deserializing the objects.

These high level streams are each chained to a low level stream, such as FileInputStream or FileOutputStream. The low level stream handle the bytes of the data.

The writeObject() method saves the state of the class by writing the individual fields to the ObjectOutputStream.
The readObject() method deserialize the object from the object output stream.

The serializable interface relies on the Java run-time default mechanism to save object’s state. (methods mentioned above)

All the referred objects by the serialized object also are converted and written to the stream. All state information necessary to reconstruct the object and referred object within, gets stored together (as it generates an object graph by serialization).

Exceptions when Serialization Does not Happen

While serializing there are few attributes who are ignored from read and write to the stream:

  1. Serialization ignores static fields because they are not part of any particular object state.
  2. Base class fields are only handled if the base class itself is serializable.
  3. Variables marked as Transient variables.

Externalizable Interface

This interface specifies that the implementing class will handle the serialization on its own, instead of relying on the default run-time mechanism. This includes which fields get written and read and in what order.

The class must define a writeExternal() method to write out the stream and readExternal() to read.

public abstract void writeExternal(ObjectOutput out) throws IOException

public abstract void readExternal(ObjectInput in) throws IOException

Being public, these methods carry the risk that a client may be able to write or read information in the object.

Example for Serialization

FileOutoutStream fileOut = new FileOutoutStream("day");
ObjectOutoutStream s = new ObjectOutoutStream(fileOut );
s.writeObject("Today");
s.writeObject(new Date());
s.flush();

ObjectOutputStream is a processing stream, so it must be constructed on another stream. This code constructs an ObjectOutoutStream on a FileOutputStream, thereby serializing the object to a file named “day”.

ObjectOutputStream implements ‘DataOutput’ interface that defines many methods for writing primitive data types. Methods examples are writeInt, writeFloat etc.

Question for you : What is serialVersionUId in terms of java serialization. Why it is recommended that every class implementing Serializable interface should have this attribute and the attribute must be final.

Previous articledoGet() vs. doPost()
Next articleServlet Questions
I have spent almost 10 years playing around Java and related technologies. I love to write on different topics and would be very much willing to hear back your feedback/suggestions on them. This site is a medium to share my knowledge with the Java folks and grow further. My other interests include traveling, driving, swimming and dance. But yes, my web site has become my passion over the time :) I live in Scotland and travel to India often, my roots being there.

NO COMMENTS

LEAVE A REPLY