Monthly Archives: December 2016

Java Object Serialization

Introduction

Mechanism where an object can be converted to a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object

Object can be serialized and stored in a file, later it can be deserialized to form an object

It is JVM independent. An object can be serialized in one platform and deserialized in other platform

Purpose of Serialization

Communication: Object can be serialized and transmitted to other machine over the network. it can be deserialized on other machine.

Persistence: If you want to store the state of a particular operation in a database, it can be easily serialized to a byte array, and stored in the database for later retrieval.

Cross JVM Synchronization: Serialization works across different JVMs that may be running on different architectures.

Conditions for a class to be serializable

The class must implement the java.io.Serializable interface or inherit that implementation from its object hierarchy

All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Transiet

A field marked as transient is not serializable. It is typically used for fields that would be irrelevant when the object is unserialized, or fields that would be less-than-safe to store e.g. passwords, decrypted data etc.

serialVersionUID

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which 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.

A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java Object Serialization Specification.

However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.