Serialization vs Externalization

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, a file or to UI pages. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called Deserialization.

Where Externalization is custom Serialization.

Note: – So the this blog is not really going to teach you how to do serialization.

So how Serialization works:

The object is serialized to a stream, which carries not just the data, but information about the object’s type, such as its version, culture, and assembly name. From that stream, it can be stored in a database, a file, or memory or shown into the UI pages.

How to achieve it:

As you know whenever we need to Serialize any class we have to implement Serializable interface. Since Serializable is a Marker Interface, it doesn’t has any method so there is no compulsion of implementing any method to serialize our class. By doing so, all class attributes/members are Serialized by JVM without asking.

But what if we don’t want to serialize all our class attributes/members.

This can be achieved in following ways:

  • You can declare your class members as static or transient,
  • Implement writeObject(ObjectOutputStream out) and readObject(ObjectInputStream in) methods for controlled Serialization. 
  • Implement Externalizable interface and implement readExternal(ObjectInput arg0) and writeExternal(ObjectOutput arg0) methods to DeSerialize and Serialize respectively.

I prefer second and third approach because by doing so you have more control over this whole process.

As I said earlier, Externalization is custom Serialization. It means, you can implement Externalizable interface and implement its methods and achieve your Serialization goal.

But if you notice we have third approach as well. i.e. Implement writeObject(ObjectOutputStream out) and  readObject(ObjectInputStream in). But from where these methods are coming? These methods are not in any class nor they are coming from any where. Instead, these methods are built-in feature of the serialization mechanism. Notice that both methods are (and must be) declared private, proving that neither method is inherited and overridden or overloaded. The trick here is that the virtual machine will automatically check to see if either method is declared during the corresponding method call. The virtual machine can call private methods of your class whenever it wants but no other objects can. Along with that make sure your class is also implementing Serializable interface while implementing above two methods.

Judgement:

If I say, There was no need of Externalizable interface at first place. It seems, one of the mistake by Java people. We can override writeObject(ObjectOutputStream out) and  readObject(ObjectInputStream in) easily and can achieve custom Serialization.

 

Hope this clear doubts!!