Tuesday, August 23, 2011

Serialization in Java

Java provides its developers with a rich set of APIs for object serialization. In this article we will look into some of the intricacies of object serialization in Java.

We shall start with the most basic example of how to serialize an object in Java; here are the high level steps:

  • Step 1: Get the object to serialize [can be null]. Let the object be o.
  • Step 2: Get a valid ObectOutputStream instance. Let the ObjectOutputStream instance be out.
  • Step 3: out.writeObject(o); will serialize the object to the stream.

Let us see the above steps in terms of a code snippet:
String s = new String(); //the object that we will serialize
ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream(“out.dat”));
out.writeObject(s); //serialize the object
Now let us look at some of the basic guidelines that should be followed for Object serialization:

1. Any class that wants its objects to be serialized must implement the Serializable interface. The Serializable interface does not have any methods. It merely serves to flag an object as serializable to an ObjectOutputStream.

2. If there any members in a Serializable class, then the following guidelines apply:

     i. If they are primitives, they are automatically serializable.

    ii. If they are non-primitive objects, they must implement Serializable. If we try to serialize an object that contains reference to an object that does not implement Serializable then while serializing the object, we get a Runtime Exception.

    iii. If we have a reference to a non-serializable object in our class, then we have to mark the reference with the keyword transient. The transient keyword on a reference means that when the parent object is serialized then the object whose reference is marked as transient will not be serialized.

Let us take a look at a simple code snippet that illustrates the above guidelines:
// a non-serializable class
public class Model
    private Integer modelID;
    private String modelName;
    //rest of the implementations

// a serializable class
public class Engine implements Serializable
    private int engineID;
    private String engineName;
    // other implementations

public class Car implements Serializable
    //a primitive, hence serializable
    private int carID; 

    //a non-serializable object, hence transient
    private transient Model carModel; 

    //a serializable object, hence no transient
    private Engine carEngine; 
    // other implementations
Now when we try to serialize an instance of a Car object, there will be no exceptions thrown because all the members of the car object are either primitives, or implement Serializable or are marked with the keyword transient.

Note that in our Car declaration if we had not marked our Model object as transient, we would have got a RuntimeException while trying to serialize the Car object.

The above example was a very basic one to show how to serialize an object in Java. Now let us look under the hood as to how Java resolves objects during serialization. To state the problem, consider the following class declarations:

public class GearType implements Serializable
    private int ID;
    private String gearName;
    //other implementations;

public class Car implements Serializable
    private int ID;
    private GearType gearType
    public Car(int i, GearType g)
        this.ID = i;
        this.gearType = g;

Now let us serialize two Car objects:

GearType g = new GearType();
Car c1 = new Car(1, g);
Car c2 = new Car(2, g);
ObjectOutputStream out = new ObjectOutputStream(

In the above code snippet, we serialized two Car objects [note the usage of the same GearType object to construct two different Car objects]. The interesting question is: how many GearType objects were serialized?

There was only one GearType object that both the Car objects were sharing. Hence it should only serialize one GearType object. The answer indeed is one. This can be proved by checking if the serialized GearType object is the same for both the Car objects. Let us look into that:
ObjectInputStream in = new ObjectInputStream(
        new FileInputStream(“out.dat”));
Car first = (Car) in.readObject();
Car second = (Car) in.readObject();
System.out.println(first.getGearType() == second.getGearType());

The above code does print true. Note that here we are testing for object identity of the GearType object instead of logical equality [which is done via equals() method]. The identity test is required because we want to verify whether both the GearType objects are actually the same.

While performing serialization of objects, Java forms a data structure similar to an Object Graph to determine which objects need to be serialized. It starts from the main object to serialize, and recursively traverses all the objects reachable from the main object. For each object that it encounters, which needs serialization, it associates an identifier that marks the object as already been serialized to the given ObjectOutputStream instance. So when Java encounters the same object that has already been marked as serialized to the ObjectOutputStream, it does nor serialize the object again, rather a handle to the same object is serialized. This is how Java avoids having to re-serialize an already serialized object. The seemingly complex problem was solved by the simple method of assigning IDs to objects. Beautiful!

One important thing to note is that if we used different ObjectOutputStream instances to serialize the two Car objects, then Java would have serialized the same GearType object twice albeit in the different streams. This is because the first time Java marks the GearType object with an ID, that ID will associate the object to the first ObjectOutputStream and the next time when Java encounters the same object for serialization it sees that this object has not been serialized to the current ObjectOutputStream and hence it will serialize it again to the new stream.

Let us illustrate this via a code snippet:
GearType g = new GearType();
Car c1 = new Car(1, g);
Car c2 = new Car(2, g);
ObjectOutputStream out1 = new ObjectOutputStream(
ObjectOutputStream out2 = new ObjectOutputStream(

Now to prove that the GearType object is indeed serialized twice, we read the streams back:

ObjectInputStream in1 = new ObjectInputStream(
        new FileInputStream(“out1.dat”));
ObjectInputStream in2 = new ObjectInputStream(
        new FileInputStream(“out2.dat”));
Car first = (Car) in1.readObject();
Car second = (Car) in2.readObject();
System.out.println(first.getGearType() == second.getGearType());

Now the above code prints false, which proves that the GearType object was serialized twice.

That is all for now. We have barely touched the surface of serialization in Java. In the next article [hopefully soon] we will take a look at other aspects of serialization like, customizing serialization, protecting classes from serialization [specifically protecting your singletons], class versioning problems etc.

Happy coding!


  1. Thanks for commenting on my post comparator and comparable in java with example , I see you have also covered Serialization in great detail with nice examples. keep it up man. By the way I also blogged my experience as Top 10 java serialization interview questions, let me know how do you find it.


    1. I have read your blog its very attractive and impressive. I like it your blog.

      Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

      Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    2. Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training

      Hibernate Online Training Hibernate Online Training Spring Online Training Spring Online Training Spring Batch Training Online Spring Batch Training Online

    3. Java Training Institutes Java Training Institutes Java EE Training in Chennai Java EE Training in Chennai Java Spring Hibernate Training Institutes in Chennai J2EE Training Institutes in Chennai J2EE Training Institutes in Chennai Core Java Training Institutes in Chennai Core Java Training Institutes in Chennai

  2. Shouldn't it be FileOutputStream in the constructor rather than FileInputStream?

  3. Well spotted! Case of an erroneous copy-paste job. Corrected now. Thanks.

  4. I need more on serialization...please post how we can make use of ID in our class and how will it affect already serialized class if an attribute is changed. Will child class also become serializable if parent is serializable also what is externalization and all that you mentioned in your last paragraph.

  5. Good one..Please provide the next section soon!!!

  6. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.
    Vee Eee Technologies

  7. really good information. useful details.

  8. very nice thanks for sharing

    hey friend see snow on google
    Type “Let It Snow” on @Google If you click and drag you can wipe the snow away. It is great. source: http://le-titsnow.blogspot.com

    1. i love this post dear. it really nice. Good information provide by this blog.
      Online MBA

  9. I wanted to thank you for this great read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post.
    source: www.wbupdates.com

  10. 1. Any class that wants its objects to be serialized must implement the Serializable interface. The Serializable interface does not have any methods. It merely serves to flag an object as serializable to an ObjectOutputStream.

    means if I implement serializable , then ObjectOutputStream.writeObject() method will call and write in heap memory?

  11. Thanks a lot, it's really good and detail entry.

  12. Many thanks for this great post.

  13. its very clear post. java training in chennai visit us @http://www.besanttechnologies.com/training-courses/java-training

  14. That is a brilliant article on dot net training in Chennai that I was searching for. Helps us a lot in referring at our dot net training institute in Chennai. Thanks a lot. Keep writing more on dot net course in Chennai, would love to follow your posts and refer to others in dot net training institutes in Chennai.

  15. I very happy to read this informative post.Its a very useful for everyone.
    java training institute

  16. I am happy to found such helpful and fascinating post that is written in well manner.
    QTP Training in Chennai | Software Testing Training in Chennai

  17. I'm very glad when read your article. It's easy to understand and very useful for newbie as me. Thank you so much and wish you happy…Professional Android Training in Chennai


  18. the blog is very interesting and will be much useful for us. thank you for sharing the blog with us. please keep on updating.
    Linux Training in Chennai

  19. .NET software development remains one of the best careers, According to polling and surveys. Lots of openings are there in market for Dot net Fresher’s & Experienced Professionals
    dot net training in chennai

  20. My Arcus offer java training with 100% placement. Our java training course that includes fundamentals and advance java training program with high priority jobs. java j2ee training with placement having more exposure in most of the industry nowadays in depth manner of java

    java training in chennai

  21. This is my first visit to your blog, your post made productive reading, thank you. dot net training in chennai

  22. Enroll for Java Training in Bangalore with DataBytes; best Java Coaching Institutes in Bangalore.

  23. You post explain everything in detail and it was very interesting to read. Thank you. nata coaching centres in chennai

  24. Superb explanation & it's too clear to understand the concept as well, keep sharing admin with some updated information with right examples.Keep update more posts.

    Manpower Consultancy in Chennai

  25. Superb blog. I really enjoyed very much with this article here. Really its a amazing article that I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article. Thank you for sharing such a great blog with us. Expecting for your update.
    PHP Training in Chennai

  26. I just see the post i am so happy to the communication science post of information's.So I have really enjoyed and reading your blogs for these posts.Any way I’ll be replay for your great thinks and I hope you post again soon...
    Web Development Company in India

  27. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in java programming your post help me a lot.Thanks for your informative article.java training in chennai | chennai's no.1 java training in chennai

  28. Excellent and very cool idea and the subject at the top of magnificence and I am happy to this post..Interesting post! Thanks for writing it.What's wrong with this kind of post exactly? It follows your previous guideline for post length as well as clarity..
    Android Training in Chennai

  29. Informative article, just what I was looking for.seo services chennai

  30. It’s the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions.You can write next articles referring to this article. I desire to read even more things about it..
    SEO Training in Chennai
    Selenium Training in Chennai
    Web Designing Training in Chennai

  31. It's like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you can do with some pics to drive the message home a little bit, but instead of that, this is fantastic blog. A great read. I will definitely be back.
    Delivery service singapore
    Singapore delivery service
    24 hour delivery singapore

  32. nice blog. thanks for sharing valuable information. It’s really good.Any one looking software courses nareshit is the best offline and online software training institute in Hyderabad and Chennai.

  33. I must thank you for the efforts you have put in spending this site. I am hoping to out the same high-grade content by you later on as well. In truth, your creative writing abilities has inspired me to get my own, personal blog now..
    Java Training in Chennai
    Dot Net Training in Chennai
    Cloud Computing Training in Chennai
    Digital Marketing Training in Chennai
    SAS Training in Chennai
    SEO Training in Chennai
    AWS Training in Chennai
    Microsoft Azure Training in Chennai

  34. we are a strong team of highly experienced IT professionals, they help us in providing website designing, website development and Digital marketing other services in the single window.

  35. Nice explanation and thanks for giving reason to write feedback on this article.
    Police Result

  36. • Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updatingAzure Online Training hyderabad

  37. very informative blog and very useful for readers. making us to learn more from your blog...
    SAP scm Training in Chennai

  38. Australia Best Tutor is one of the best Online Assignment Help providers at an affordable price. Here All Learners or Students are getting best quality assignment help with reference and styles formatting.

    Visit us for more Information

    Australia Best Tutor
    Sydney, NSW, Australia
    Call @ +61-730-407-305
    Live Chat @ https://www.australiabesttutor.com

    Our Services

    Online assignment help
    my assignment help Student
    Assignment help Student
    help with assignment Student
    Students instant assignment help

  39. Learn how our role-based and specialty certifications help you demonstrate your deep AWS knowledge. Credo Systemz provides the best AWS Training to get your certifications easily.

    AWS is designed to allow application providers, ISVs, and vendors to quickly and securely host your applications. Credo Systemz provides the best AWS Training to get your certifications easily.

    aws training in chennai with placement

    aws authorized training partner in chennai

    aws solution architect training in chennai

    aws training in velachery

    aws training in OMR

    aws certification training in Chennai

    aws course in chennai what is the qualificationThanks for sharing,

  40. Thanks for the informative article.This is one of the best tips in my life. I have in quite some time.Nicely written and great info.I really cannot thank you enough for sharing.

    Apartments in Chennai

  41. Each department of CAD have specific programmes which, while completed could provide you with a recognisable qualification that could assist you get a job in anything design enterprise which you would really like.

    AutoCAD training in Noida

    AutoCAD training institute in Noida

    Best AutoCAD training institute in Noida

  42. Nice Article..thanks for sharing very useful information
    Thank you...
    python online training in hyderabad

  43. Nice article.. was very useful and informative.

  44. This is a 2 good post. This post gives truly quality information.

    RPA Training in Hyderabad

  45. It's very nice blog. I'm so happy to gain some knowledge from here.

    MSBI Training in Hyderabad

  46. interesting blog, here lot of valuable information is available, it is very useful information. we offers this Java classroom and online training at low caste and with real time trainers. please visit our site for more details Java training

  47. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..
    what is ibm datapower

  48. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
    Java training in Chennai | Java training in Omr

    Oracle training in Chennai

    Java training in Chennai | Java training in Annanagar

    Java training in Chennai | Java training institute in Chennai | Java course in Chennai

  49. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..
    python course in pune
    python course in chennai
    python course in Bangalore

  50. This is a good post. This post give truly quality information. I’m definitely going to look into it. Really very useful tips are provided here. thank you so much. Keep up the good works.
    angularjs-Training in chennai

    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    angularjs-Training in pune

  51. Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

  52. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.

    rpa training in Chennai | rpa training in bangalore | best rpa training in bangalore | rpa course in bangalore | rpa training institute in bangalore | rpa training in bangalore | rpa online training

  53. Thanks for sharing this unique information with us. Your post is really awesome. Your blog is really helpful for me..
    Top college in Jaipur|law college|law college in Jaipur|Best law college in Jaipur

  54. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.
    AWS Interview Questions And Answers | Top 250+AWS Interviews Questions and Answers –Besant Technologies
    Best AWS Interview questions and answers | Top 110+AWS Interview Question and Answers
    Best and Advanced AWS Training in Bangalore | Best Amazon Web Services Training in Bangalore
    Advanced AWS Training in Pune | Best Amazon Web Services Training in Pune
    Advanced AWS Online Training | Best Online AWS Certification Course in india

  55. What are tips for data science interviews?
    Be confident! (I am not afraid of strong/confident - just the opposite!)
    If you do not know the answer - I will appreciate you more if you would say: "I need to go back home and read about it more"
    Creativity (open your mind) is the secrete ingredient to become a great Data Scientist, and not just "A Data Scientist".
    Please make sure you are familiar with simple concepts in probability theory and linear algebra.
    I hope I didn't reveal too many secrets, now try to make yourself familiar with these questions - and good luck in the interviews :) If you want more details to contact us: #Livewire-Velachery,#DataScienceTraininginChennai,#DataScienceTrainingInstituteinChennai,#TrainingInstituteinvelachery,#DataScience, 9384409662,

  56. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs interview questions and answers

    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs-Training in pune

  57. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    Online DevOps Certification Course - Gangboard
    Best Devops Training institute in Chennai

  58. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    python Online training in chennai
    python Online training in bangalore
    python interview question and answers