Thursday, September 07, 2006

Java Serialization Best Practices

Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket.

Deserialization is the process of reading back that serialized java object stream from input stream.

A java object is serializeable and deserializeable if that class follows the following rules

A) The java class must implement java.io.Serializable interface or java.io.Externalizable interface or inherit that implementation from any one of it's super class implementation.

B) All instance variables of that class must implement Serializable interface or Externalizable interface or inherit from one of it's super class.

All primitive data types and some of standard java API classes are serializable. You need not explicitly implement Serializable or Externalizable interfaces for those classes. Serialization process ignores class (static) variables.

Externalizable interface allow to do your own custom implementation of serialization. In this section,  focus is only on Serializable interface.

We will talk initially about Serializable interface. This is a marker interface and does not have any methods. All major java technologies like RMI, EJB are based on serialization process to pass the objects through network. These technologies implicitly do all the serialization work for you. You need to simply implement the java.io.Serialzable interface, but If you want to do your own serialization, that is reading from or writing to streams, ObjectInputStream and ObjectOutputStream  can be used.

Best Practices

  1. Use 'transient' key word for unnecessary variables that need not be read from/written into streams.
  2. When you write RMI, EJB or any other technologies that uses built in Serialization to pass objects through network, use 'transient' key word for unnescessary variables.
  3. Class (static) variables ignores by Serialization process like 'transient' variables.

Get more information

Tags: java, java serialization, best practices, transient, streams, RMI, serializable, externalizable, java API

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Comments on "Java Serialization Best Practices"