Sunday, April 17, 2011

Externalization vs serialization


Serialization uses certain default behaviors to store and later recreate the object. You may specify in what order or how to handle references and complex data structures, but eventually it comes down to using the default behavior for each primitive data field.
Externalization is used in the rare cases that you really want to store and rebuild your object in a completely different way and without using the default serialization mechanisms for data fields. For example, imagine that you had your own unique encoding and compression scheme.
However, transient keyword though bridges the gap between the two, as now we have control of which field to serialize and which not.
There is one major difference between serialization and externalization: When you serialize an Externalizable object, a default constructor will be called automatically; only after that will the readExternal() method be called.

Final words on serialization and externalization:
In earlier version of Java, reflection was very slow, and so serializaing large object graphs (e.g. in client-server RMI applications) was a bit of a performance problem. To handle this situation, the java.io.Externalizable interface was provided, which is like java.io.Serilizable but with custom-written mechanisms to perform the marshalling and unmarshalling fuctions (you need to implement readExternal and writeExternal methods on your class). This gives you the means to get around the reflection performance bottleneck.

In recent versions of java (1.3 onwards, certainly) the performance of reflection is vastly better than it used to be, and so this is much less of a problem.

Also, the built-in Java serialization mechanism isn't the only one, you can get third-party replacements, such as JBoss Serialization, which is considerably quicker, and is a drop-in replacement for the default.

A big downside of Externalizable is that you have to maintain this logic yourself - if you add, remove or change a field in your class, you have to change your writeExternal/readExternal methods to account for it, as mentioned in post on limitations of serialization.

In summary, Externalizable is of the Java 1.1 days. There's really no need for it any more. Only
when you need it very much, than only use it.


Referenceshttp://download.oracle.com/javase/tutorial/javabeans/persistence/index.html

1 comment:

Chitika