Java Serialization

What is serialization?

The process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time.

What can I use?

The Java Serialization API.

The Rules

Rule #1: The object to be persisted must implement the Serializable interface or inherit that implementation from its object hierarchy.

To persist an object in Java, we must have a persistent object. An object is marked serializable by implementing the java.io.Serializable interface, which signifies to the underlying API that the object can be flattened into bytes (and subsequently inflated in the future).

public class PersistedClass implements Serializable

Rule #2: The object to be persisted must mark all nonserializable fields transient

On the other hand, certain system-level classes such as Thread, OutputStream and its subclasses, and Socket are not serializable. These should be marked transient since it doesn't make sense to serialize them.

transient private Thread notserialthread;

Version control Gotcha!

Imagine you have a serialized flattened object sitting in your file system for sometime. Meanwhile, you update the class file, perhaps adding a new field. What happens when you try to read in the flattened object?

An java.io.InvalidClassException will be thrown! -- because all persistent-capable classes are automatically given a unique identifier. If the identifier of the class does not equal the identifier of the flattened object, the exception will be thrown.

If you wish to control versioning, you simply have to provide the serialVersionUID field manually and ensure it is always the same, no matter what changes you make to the classfile.

How? JDK distribution comes with a utility called serialver which returns the generated serialVersionUID. (it is just the hash code of the object by default).


Simply copy the returned line with the version ID and paste it into your code.

The version control works great as long as the changes are compatible. Compatible changes include adding or removing a method or a field. Incompatible changes include changing an object's hierarchy or removing the implementation of the Serializable interface.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

manveen

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today