What is object serialization?

316,340

Solution 1

Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object.

Solution 2

You can think of serialization as the process of converting an object instance into a sequence of bytes (which may be binary or not depending on the implementation).

It is very useful when you want to transmit one object data across the network, for instance from one JVM to another.

In Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable.

You can also prevent some data in your object from being serialized by marking the attribute as transient.

Finally you can override the default mechanism, and provide your own; this may be suitable in some special cases. To do this, you use one of the hidden features in java.

It is important to notice that what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized.

Here is a very basic sample with comments to facilitate its reading:

import java.io.*;
import java.util.*;

// This class implements "Serializable" to let the system know
// it's ok to do it. You as programmer are aware of that.
public class SerializationSample implements Serializable {

    // These attributes conform the "value" of the object.

    // These two will be serialized;
    private String aString = "The value of that string";
    private int    someInteger = 0;

    // But this won't since it is marked as transient.
    private transient List<File> unInterestingLongLongList;

    // Main method to test.
    public static void main( String [] args ) throws IOException  { 

        // Create a sample object, that contains the default values.
        SerializationSample instance = new SerializationSample();

        // The "ObjectOutputStream" class has the default 
        // definition to serialize an object.
        ObjectOutputStream oos = new ObjectOutputStream( 
                               // By using "FileOutputStream" we will 
                               // Write it to a File in the file system
                               // It could have been a Socket to another 
                               // machine, a database, an in memory array, etc.
                               new FileOutputStream(new File("o.ser")));

        // do the magic  
        oos.writeObject( instance );
        // close the writing.
        oos.close();
    }
}

When we run this program, the file "o.ser" is created and we can see what happened behind.

If we change the value of: someInteger to, for example Integer.MAX_VALUE, we may compare the output to see what the difference is.

Here's a screenshot showing precisely that difference:

alt text

Can you spot the differences? ;)

There is an additional relevant field in Java serialization: The serialversionUID but I guess this is already too long to cover it.

Solution 3

Daring to answer the 6-year-old question, adding just a very high-level understanding for people new to Java

What is Serialization?

Converting an object to bytes

What is Deserialization?

Converting bytes back to an object (Deserialization).

When is serialization used?

When we want to Persist the Object. When we want the object to exist beyond the lifetime of the JVM.

Real World Example:

ATM: When the account holder tries to withdraw money from the server through ATM, the account holder information like withdrawal details will be serialized and sent to the server where the details are deserialized and used to perform operations.

How serialization is performed in java.

  1. Implement java.io.Serializable interface (marker interface so no method to implement).

  2. Persist the object: Use java.io.ObjectOutputStream class, a filter stream which is a wrapper around a lower-level byte stream (to write Object to file systems or transfer a flattened object across a network wire and rebuilt on the other side).

  • writeObject(<<instance>>) - to write an object
  • readObject() - to read an serialized Object

Remember:

When you serialize an object, only the object's state will be saved, not the object's class file or methods.

When you serialized a 2-byte object, you see 51 bytes serialized file.

Steps how the object is serialized and de-serialized.

Answer for: How did it convert to 51 bytes file?

  • First writes the serialization stream magic data (STREAM_MAGIC= "AC ED" and STREAM_VERSION=version of the JVM).
  • Then it writes out the metadata of the class associated with an instance (length of the class, the name of the class, serialVersionUID).
  • Then it recursively writes out the metadata of the superclass until it finds java.lang.Object.
  • Then starts with the actual data associated with the instance.
  • Finally writes the data of objects associated with the instance starting from metadata to the actual content.

you can also check my Youtube video explanation here

Edit : Reference link to read.

This will answer a few frequent questions:

  1. How not to serialize any field in the class.
    Ans: use transient keyword

  2. When child class is serialized does parent class get serialized?
    Ans: No, If a parent is not extending the Serializable interface parents field don't get serialized.

  3. When a parent is serialized does child class get serialized?
    Ans: Yes, by default child class also gets serialized.

  4. How to avoid child class from getting serialized?
    Ans: a. Override writeObject and readObject method and throw NotSerializableException.

    b. also you can mark all fields transient in child class.

  5. Some system-level classes such as Thread, OutputStream, and its subclasses, and Socket are not serializable.

Solution 4

Serialization is taking a "live" object in memory and converting it to a format that can be stored somewhere (eg. in memory, on disk) and later "deserialized" back into a live object.

Solution 5

I liked the way @OscarRyz presents. Although here i am continuing the story of serialization which was originally written by @amitgupta.

Even though knowing about the robot class structure and having serialized data Earth's scientist were not able to deserialize the data which can make robots working.

Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:

Mars's scientists were waiting for the complete payment. Once the payment was done Mars's scientists shared the serialversionUID with Earth's scientists. Earth's scientist set it to robot class and everything became fine.

Share:
316,340
Warrior
Author by

Warrior

I am a software engineer.I have to learn lot in this field.

Updated on March 07, 2022

Comments

  • Warrior
    Warrior over 2 years

    What is meant by "object serialization"? Can you please explain it with some examples?

  • Jim Anderson
    Jim Anderson over 15 years
    "...so that it can be stored on a hard drive." Or transferred via a binary protocol.
  • OscarRyz
    OscarRyz over 11 years
    @raam86 instance is the object being serialized. You may think in the main method as a separate program which creates an object of type SerializationSample
  • OscarRyz
    OscarRyz over 11 years
    @raam86 is the first statement in the main method: SerializationSample instance = new SerializationSample(); then the output is created and the object written to that output.
  • raam86
    raam86 over 11 years
    Oh. Didnt folow close enough. Great!!
  • jacktrades
    jacktrades over 11 years
    What would happen if you don't implement Serializable? How would that file be changed?
  • OscarRyz
    OscarRyz over 11 years
    @jacktrades Why don't you try it. Just copy/paste the example and see "NotSerializableException" being thrown :)
  • Chris Bennett
    Chris Bennett almost 11 years
    @jacktrades because the computer hasn't been told that the object is allowed to be serialized :) what is meant by oos?
  • Chris Bennett
    Chris Bennett almost 11 years
    nevermind I found out that's the object but I'm getting the following error: cannot find symbol symbol: class ObjectOutputStream location: class Article
  • Francisco Corrales Morales
    Francisco Corrales Morales almost 10 years
    is this obligatory ? do I must serialize data before sending it? what format is it converted to ?
  • TarkaDaal
    TarkaDaal almost 10 years
    @FranciscoCorralesMorales - Behind the scenes, all data will be serialized before it is sent over a stream. How much you need to do, and what format it will be in, are both dependent on which platform and libraries you are using.
  • JAVA
    JAVA almost 10 years
    @FranciscoCorralesMorales How you are saying it? i mean you are saying the format depends on platform and libraries.I really want to know the format.
  • user207421
    user207421 almost 9 years
    When you add an answer to a six-year old question that already has several very good answers, you need to do a lot better than a cacophony of spelling errors.
  • user3437460
    user3437460 over 8 years
    I really like explanations with simple words which is succinct and clear. (+1)
  • Konstantinos Chertouras
    Konstantinos Chertouras over 7 years
    @ejp Downvoting is the tool to express your negative opinion. Being offensive and borderline rude is unacceptable.
  • user207421
    user207421 over 7 years
    @KonstantinosChertouras Giving reasons for the downvote is helpful to the poster, and those are my reasons, like them or not as you will.
  • user207421
    user207421 almost 7 years
    'Serialization is the process of serializing the state of an object is represented and stored in the form of a sequence of bytes' is meaningless. If the serialVersionUID is different it will throw an InvalidClassException, not a ClassCastException. It isn't necessary to waste all that space respecifying the serialVersionUID computation. Documentation is quoted, at excessive length, but not linked or properly cited. Too much fluff here and too many errors.
  • user207421
    user207421 almost 7 years
    This does not answer the 'what is' or 'please explain' parts of the question.
  • user207421
    user207421 almost 7 years
    You also need to avoid errors such as asserting that Serialization has a security purpose. It doesn't.
  • user207421
    user207421 almost 7 years
    'Serialization is the process of serializing' remains meaningless.
  • KingKongCoder
    KingKongCoder almost 7 years
    Android uses the hidden features that @OscarRyz mentioned to implement Parcelable which is modification of serializable to improve performance by reducing the amount of objects created during implementation.
  • Yash
    Yash over 6 years
    @EJP I have updated my post, corrected that Serialization is not for security purpose, but it is used to transform the state of an Object to any Storage and to get the original state of an object back using SUID through deserializing mechanisum. JVM to JVM
  • user207421
    user207421 over 6 years
    Spelling errors remain; also the incorrect assertions about Serializable informing the compiler; also the complete confusion between what you are quoting and what you are contributing yourself'.
  • Yash
    Yash over 6 years
    @EJP if their are spelling errors in my post, then any one can correct it. You are getting most confused on my post why So? Confused on which line. you can mention over a comment so that i can correct it if possible.
  • Nobi
    Nobi almost 6 years
    thank you very much for this succinct answer, it was very helpful!
  • yuxh
    yuxh over 5 years
    can you tell me more about "which may be binary or not depending on the implementation", I am confused by "byte sequence".Need not everything in memory be binary?
  • OscarRyz
    OscarRyz over 5 years
    @yuxh it can be also a comma separated string. class O { String s="c"} can be serialized (using a custom serializer) to something like : `"class:O","c". Serialization is not always in binary format, it could be XML, JSON, YAML, as well as many other non binary formats.
  • yuxh
    yuxh over 5 years
    so it's wrong to equal "sequence of bytes " with "binary"?how can I understand "sequence of bytes "? since the serilized format "class:O","c" will finally convert to binary ,can I think JSON etc format serializer work above binary format like Thrift ?
  • Rumado
    Rumado about 5 years
    Is it applicable to only objects ? Can we serialize variables (declared without using objects) ?
  • linjiejun
    linjiejun almost 5 years
    @Rumado Objects only
  • Andrew Anderson
    Andrew Anderson over 2 years
    "conversion of an object to a series of bytes" -- what was the object before that? I mean, anyway everything in a computer are bytes. Excuse my laymanship.