Java Serialization

23/11/2009

Have you ever seen what is inside a serialized object? I will explain you what is java serialization, then provide you with a sample for serialization. Finally most importantly, lets explore what is inside a serialized object and what it means. That is internals of java serialization and how does it works. If you want to have your own implementation of java serialization, this article will provide you with a good platform to launch.

What is Java Serialization?

Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy.

Why I used ‘primary purpose’ in the above definition is, sometimes people use java serialization as a replacement for database. Just a placeholder where you can persist an object across sessions. This is not the primary purpose of java serialization. Sometimes, when I interview candidates for Java I hear them saying java serialization is used for storing (to preserve the state) an object and retrieving it. They use it synonymously with database. This is a wrong perception for serialization.

How do you serialize?

When you want to serialize an object, that respective class should implement the marker interface serializable. It just informs the compiler that this java class can be serialized. You can tag properties that should not be serialized as transient. You open a stream and write the object into it. Java API takes care of the serialization protocol and persists the java object in a file in conformance with the protocol. De-serialization is the process of getting the object back from the file to its original form.

Here protocol means, understanding between serializing person and de-serializing person. What will be the contents of 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.

Sample Source Code for Java Serialization

package com.javapapers.sample;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class SerializationBox implements Serializable {

	private byte serializableProp = 10;

	public byte getSerializableProp() {
		return serializableProp;
	}
}

public class SerializationSample {

	public static void main(String args[]) throws IOException,
			FileNotFoundException, ClassNotFoundException {

		SerializationBox serialB = new SerializationBox();
		serialize("serial.out", serialB);
		SerializationBox sb = (SerializationBox) deSerialize("serial.out");
		System.out.println(sb.getSerializableProp());
	}

	public static void serialize(String outFile, Object serializableObject)
			throws IOException {
		FileOutputStream fos = new FileOutputStream(outFile);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(serializableObject);
	}

	public static Object deSerialize(String serilizedObject)
			throws FileNotFoundException, IOException, ClassNotFoundException {
		FileInputStream fis = new FileInputStream(serilizedObject);
		ObjectInputStream ois = new ObjectInputStream(fis);
		return ois.readObject();
	}
}

Exploring Java Serialization

Look at following image. After serializing ‘SerializationBox’ in the above sample code, I opened the output in a hex editor. You can use Notepad++ and hex plugin to open the serialized file.

Let us look at contents byte by byte and find out what they are. It starts with “ac ed”. It is is called STREAM_MAGIC. It is a magic number (java API guys says) that is written to the stream header. It denotes that is start of serialzed content.Serialized Output

Similarly every character has a meaning. Actually the serialized file is more bulkier than you would expect, as it has a huge header the meta information of the classes involved and finally the content. Object Serialization Stream Protocol have a look at chapter 6.4.2 Terminal Symbols and Constants. It gives you list of symbols and constants used in serialization.

Decrypting Serialized Java Object

In the image, I have underline a unit of information in a separate color for you to easily identify.

ac ed – STREAM_MAGIC – denotes start of serialzed content
00 05 – STREAM_VERSION – serialization version
73 – TC_OBJECT – new Object
72 – TC_CLASSDESC – new Class Descriptor
00 26 – length of the class name
63 6f 6d 2e 6a 61 76 61 70 61 70 65 72 73 2e 73 61 6d 70 6c 65 2e 53 65 72 69 61 6c 69 7a 61 74 69 6f 6e 42 6f 78 – class name
57 fc 83 ca 02 85 f0 18 – SerialVersionUID
02 – this object is serializable
00 01 – count of properties in the serialzed class – one property in our example
42 00 10 – private byte
73 65 72 69 61 6c 69 7a 61 62 6c 65 50 72 6f 70 78 70 – property name – serializableProp in our example
0a – 10 the value – This is the persisted value of the property in our sample

Thanks for the insight on serialization

ken on December 4th, 2009 11:37 pm

Serialization Concept explained nicely. Thanks for Details.

Prafulla on December 5th, 2009 1:31 am

Simple and easy-to-understand explanation. I liked the use of a broad use tool like notepad++ and the Constant mapping. By the way, in wich class this constans are defined?

Omar on December 8th, 2009 9:59 pm

Excellent technical stuff, i ever came across on Blogs. Looking forward for new subjects

Ganesh Bhosale on December 9th, 2009 7:15 am

Omar, have a look at java API:

http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectStreamConstants.html

it contains java serialization related constants.

Joe on December 17th, 2009 9:56 am

Thanks so much for the good explanation on serialization

Suresh on December 17th, 2009 9:52 am

Thanks for such a precise and clear understanding.

Shadab on December 29th, 2009 7:32 am

Very neatly explained…!

Arpit on December 29th, 2009 2:58 pm

[...] Also know some fundamentals of serialization. [...]

Serialize / De-Serialize &hellip on January 9th, 2010 2:26 pm

Today only I visited this site for the first time and wow..I am in love with its content….very informative indeed. Well its now in my fav list and I have planned to read one topic per day.

Thanks a lot for creating such a useful blog!!!

Sandeep Kumar on January 12th, 2010 4:27 pm

Hi there,

Nice Explanation in simple and precise format.
keep writing :) .

Cheers
Nitin.V

Nitin on February 6th, 2010 9:20 am

You made serialization concept just so simple and understandable.

Thanks and keep such articles coming up!

Neha J on February 10th, 2010 10:07 pm

Nice and easily understandable explanation for java serialization. I have never came across this before.

Srilatha,K on March 31st, 2010 4:43 pm

Good Insight

Jill on April 9th, 2010 11:41 am

Very Good Explanation. Its very understandable.Thanks

Sridhar on April 13th, 2010 5:02 pm

Nice understanding explanation..

Thanks a lot

Brijesh on June 17th, 2010 4:13 am

Hi

Thanks the detail explanation.

Regards,
Suwarna

Suwarna on June 24th, 2010 3:09 pm

Hi,
It is very good material on serialization. But i have one doubt.

In EJB we have ejbActivate() and ejbPassivate() methods. In CMP beans the container will serialize the object in ejbActivate() and deserialize in ejbPassivate() methods. Here we are not tranporting the objects via streams to other PCs using serialization protocol. Please explain me in the context of EJB serialization and deserialization?

Thanks

Anand Garlapati.

Anand Garlapati on July 27th, 2010 12:34 pm

Thanks for giving me this type of information.
This is a very nice and easy to understande.

divya on September 15th, 2010 4:18 am

Good information.
Thanks

Usman on September 22nd, 2010 7:27 pm

You can get more details here

http://www.javaworld.com/community/node/291
5

Akhilesh Balakrishnan on November 22nd, 2010 9:20 am

Hi,

Just to add while writing Serializable class , its good practice to put a Seriazlizable alert in file so that when some one else add a new field in the class he must ensure that field is either transient or Serializable , so that Serializability of class should not break.

Thanks
Javin

Javin @ Tibco RV Tutorial on January 28th, 2011 4:18 pm

Thanks 4 clearing my serialization concept.

Shampa on March 7th, 2011 6:58 pm

very cool

rohan on March 9th, 2011 8:10 am

See this

sdfsd on April 5th, 2011 6:38 am

[...] serialization, single instance contract of the singleton pattern can be violated. You can serialize and [...]

Singleton Pattern&hellip on May 2nd, 2011 12:46 am

Explained very nicely and each line has clear message………….

Prahlad Gupta on May 5th, 2011 5:40 am

Nice to see detail description,it helps alot to understand internal details.

Please keep posting such a nice blogs.

-Vidhi

vidhi on May 5th, 2011 10:26 am

[...] 使用序列化,单例模式与单例模式之间存在冲突。你可以序列化然后反序列化来获取新的相同的单例模式的类的实例。使用Java API,你可以实现如下的方法并从流中读取来覆盖实例。你可以确保总是有一个唯一的实例。 [...]

单例模式 | Java视点&hellip on May 16th, 2011 9:58 am

Really good knowledge i got on java serialization

Thanks
Prasanna

Anonymous on May 18th, 2011 2:21 pm

Explained in a very Simple Manner.
Thank You.

Akshata on June 22nd, 2011 4:55 am

Great Blog!!!!!Nice job Done Joe:)

Anji on June 23rd, 2011 8:07 am

Its very nice artice , but please cover the Serialization UID concept indetail.

Madhukar Gunda on July 6th, 2011 11:45 am

good knowledge i got on java serialization, but please trasiant varible concept indetails.

anji on July 8th, 2011 8:00 am

WOW…..SUPERB GOOD JOB DUDE…Continue with super stuff

sridip on July 11th, 2011 5:17 pm

Can i serialise any type of data,means i want to serialise print preview.is it possible???????

swathi on July 12th, 2011 8:46 am

The explanation is very simple and clear. Thanks.

sha on July 19th, 2011 11:54 am

very nice stuffs :)
beautiful way of presenting :)
Thank you very much :)
Sandeep

Anonymous on July 23rd, 2011 3:49 pm

Great Thanks Joseph :-)

Bharath narla on July 28th, 2011 4:50 pm

Its very nice artice , but please cover the Serialization whole concept in detail

Jitendra Gupta on August 9th, 2011 5:37 am

Nice Article. Explained in simple manner.

Mayank Modi on August 22nd, 2011 7:25 am

Can you explain the Serialization using Externalizable interface?

thanks in advance.

Gourav on August 23rd, 2011 4:51 am

Serialization Concept has been explained in a simple but easily understandable manner….
Its really cool…

Jagadish.K on August 24th, 2011 9:16 am

Thank u for ur answer….!:-)

Sakthi Manoj on August 26th, 2011 1:04 pm

Very Knowledge full about Serialization

Ashok Kumar on September 14th, 2011 6:24 pm

nice one,it is very easy to understand…
Thanks

govardhan on September 16th, 2011 6:06 am

Very nicely explained.
Good blog.

Thanks
Neha T

Neha T on September 16th, 2011 8:55 am

very nice… at last found a good website 4 java learning

sonal on September 26th, 2011 2:57 pm

can we implement Serialization on images…
basically i want image to be converted in binary form..
pls reply

sonal on September 26th, 2011 2:58 pm

easy way to learn from this site……?

Ashish jain on September 29th, 2011 8:15 am

very nice discription
thamks alit!!!!!!!!!!!!!!!!!

Ashish Gokhale on October 1st, 2011 8:37 am

Thanks for providing such tough topic in an easiest way…..

Nagraj on October 3rd, 2011 1:16 pm

very helpful, thanks.

wudeng on October 10th, 2011 3:00 am

Hi
Thanks for such a great post….

Eman Zaman on October 18th, 2011 5:25 am

Very nice. Above contents are helpful to all.

Thanks for such a great work.

Could you please add more examples like serializing images or Resultset,It will be more helpful

muthu on October 20th, 2011 7:39 am

i could not understand
“serialization”

jnana on October 21st, 2011 9:25 am

something good in this………

sathish on October 27th, 2011 1:25 pm

Excellent creativity.

Basavaraj on November 1st, 2011 1:46 pm

SIR AWESOME CODE AND EXCELLENT AND STUDENTS ARE EXACTLY IMPROOVING THERE KNOWLEDGE AUTOMATICALLY BY READ THIS CONCEPT

THANKING YOU SIR ,

RAJ on November 6th, 2011 4:51 pm

Hi this is good

santhosh on November 9th, 2011 9:24 am

thanks to this site develpers

sumit on November 9th, 2011 12:12 pm

Can you give some explanation about SerialVersionUID in serialization

John on November 11th, 2011 11:18 am

I appreciated it.It is very nice explanation.

sunil kumar chaurasia on November 14th, 2011 9:11 am

sir I want to some easy example of file handling,java bean,and networking.I need must.
thank u sir

sunil kumar chaurasia on November 14th, 2011 9:13 am

it is a good material for serialization….

easily understandable

Ramkrishna on November 28th, 2011 11:01 am

Thnks!!!

azaz ahmed on November 28th, 2011 12:27 pm

this is very good nodes

ASHOK CHOWDARY on November 29th, 2011 8:57 am

Thanks a lot .I came to know a lot about SERIALIZATION .

Anonymous on December 6th, 2011 10:39 am

[...] Construction in Serialization 11/12/2011My previous article on exploring java serialization is a box office hit. In continuation to that and popular request, I am going to write on how [...]

Object Construction in Se&hellip on December 11th, 2011 6:26 am

Nice job……….
Thank a lot….

Guna on December 13th, 2011 2:30 pm

Kuddos to ur explanation

Praveen on December 16th, 2011 11:28 am

awesome yaar………
got to know something new and real helpful
and easy to unerstand..

thnx…

keep it up…..

karan on December 17th, 2011 1:17 pm

nice…

biswajit on December 18th, 2011 6:01 pm

[...] have seen enough about using the default protocol to implement serialization and how instances are created during serialization. In this current article we shall see about [...]

Customize Default Seriali&hellip on December 18th, 2011 11:49 pm

Please tell me the difference between serialization, transcient and clonable?.

Dinesh on December 19th, 2011 12:23 pm

This is awesome. I am very much clear about serialization

muthu on January 1st, 2012 11:30 am

Nicely Explained. Good work dude….
Keep Posting different Topics On java.
thx

rajeshwar on January 4th, 2012 1:56 pm

Really nice explanation……….

Swaminathan on January 6th, 2012 7:59 am

hey really nice blog… keep it up
very good explanation
thank u….

abhijit on January 10th, 2012 1:03 pm

please tell how to serialize object in xml

mazhar on January 11th, 2012 11:07 am

thanks to make us understand.
please tell how we use xml in serialization.
and how we convert object to xml form.

mazhar on January 11th, 2012 11:12 am

Excellent Material.

Harish on January 13th, 2012 10:37 am

[...] is an interface that enables you to define custom rules and your own mechanism for serialization. Serializable defines standard protocol and provides out of the box serialization [...]

Externalizable vs Seriali&hellip on January 16th, 2012 5:07 am

Hi Joe , can you explain why strings are immutable in java???

rahul on January 17th, 2012 3:49 pm

awesome Tutorial for Serialization

SuresHK on January 17th, 2012 6:16 pm

@rahul have a look at java string

Joe on January 17th, 2012 8:57 pm

Very neat and clear explanation which never read.

Anonymous on January 22nd, 2012 4:21 pm

its very nice def….

Sunil Kumar on January 24th, 2012 10:24 pm

Hi,
This is very helpful example….

Thanks
Sunil Kumar

Sunil Kumar Maghar on January 24th, 2012 10:29 pm

Good

prakash on January 25th, 2012 11:53 am

Nice way of presentation.

I have a question regarding de-serialization.
First you serialize a object SerializationBox and write it to a file outfile.ser. On a different JVM i take the outfile.ser file and try to deserialize it using readObject() but i get java.lang.ClassNotFoundException as there is no class file sent.

How does it reconstruct the object and type cast to the SerializationBox object?

I know the file contains Class information as shown in the hex-format. but how do you write code to use readObject and typecast to the serialized object.

SerializationBox reconstructedSBX = SerializationBox ois.readObject();

Ganesh Machkure on January 27th, 2012 9:03 pm

toooooooooooooo good

Anonymous on February 6th, 2012 2:21 pm

Excellent work Joe!!
- Shyam :)

Anonymous on February 6th, 2012 4:32 pm


Email:

about
I am Joe, author of this blog. I run this with loads of passion. If you are into java, you may find lot of interesting things around ...more about me. Google+
java badge
Home