Wednesday, June 14, 2017

Serialization/Deserialization

Serialization
process of conversion of one object state to another object state so that the object can be easily stored(file/memory/db) or transmitted(network).

Deserialization
process of reconstruction of object from a series of bytes according to the serialization format. i.e creating a semantically identical clone/replica of the original object.

This process of serializing an object is also called marshalling an object.
This process of deserializing an object is also called unmarshalling an object.

Note:- what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized.

What is serialVersionUID?
Each time an object is serialized, the object is stamped with a version ID number for that object's class.This ID number is called serialVersionUID and it is computed based on information about the class structure(based on the fields/methods that are defined in the class).
If you do not explicitly declare a serialVersionUID, JVM will do it for you automatically. This serialVersionUID is used for version control of object.

Why use serialVersionUID?
This number is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.

Example:- Suppose you made an Employee class and it has version id #333 (assigned by JVM),Now when you will serialize the object of that class (Suppose Employee object), JVM will assign UID to it as #333.

Consider a situation - in the future you need to edit or change your class and in that case when you modify it, JVM will assign it a new UID (Suppose #444). Now when you try to deserialize the employee object, JVM will compare serialized object's (Employee object) version ID(#333) with that of the class i.e #444(Since it was changed). On comparison JVM will find both version UID are different and hence Deserialization will fail. Hence if serialVersionUID for each class is defined by programmer itself. It will be same even if the class is evolved in future and hence JVM will always find that class is compatible with serialized object even though the class is changed.

Related Exception:-
java.io.NotSerializableException
java.io.InvalidClassException
   

No comments:

Post a Comment

Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...