Monday, 17 June 2019

Serialization | Serializable vs Externalization in Java



Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.




Serializable vs Externalization in Java
Knowing the difference between Externalizable vs Serializable is important to make a better informed decision for performance improvement for applying serialization into your application.
  • Serializable is a marker interface i.e. it doesn’t contain any method. However, the Externalizable interface contains two methods readExternel() and writeExternal()  which need to be overridden in implementing class.
  • Serializable interface passes the responsibility of serialization to JVM to use its default algorithm while Externalizable provides control of serialization logic to the developer – to write custom logic.
  • Mostly, default serialization is easy to implement but has a higher performance cost. Serialization is done using Externalizable, add more responsibility to the developer but often result in better performance.
  • In the case of Serializable, It’s hard to analyze and modify class structure because any change may break the serialization. However, It’s easier to analyze and modify class structure because of complete control over serialization logic in Externalizable.
  • Default serialization does not call any class constructor.  However, a public no-argument constructor is required while using Externalizable interface.

Key Points
  • JVM gives call back to readExternel() and writeExternal() of java.io.Externalizalbe interface for restoring and writing objects into persistence.
  • Though Externalizable provides complete control, it also presents challenges to serialize super type state and take care of default values in case of transient variable and static variables in Java.
  • If used correctly Externalizable the interface can improve performance of the serialization process.
  • Externalizable interface is child interface of Serializable i.e. Externalizable extends Serializable. So if any class implements Externalizable interface and override it’s writeExternal() and readExternal() methods then first preference is given to these methods over the default serialization mechanism provided by JVM.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...