Difference between Serialization and Externalization in Java

JavaObject Oriented ProgrammingProgramming

Serialization and externalization both are the processes of converting an object to stream byte and storing byte stream in database or memory. The class which implements java.io.Serializable interface can be serialized. On the other hand, externalization used for custom serialization based on the requirement in the application. Externalization extends java.io.Serializable. 

Sr. No.KeySerializationExternalization
1
Interface
Serialization is a marker interface 
Externalization contains two methods readExternal and writeExternal. 

Implementation logic 
The class which is implementing this interface gives the responsibility to JVM for serializing or persist java object.  JVM use readObject and writeObject for serialization 
Externalization provides implementation logic control to the application by overriding readExternal and writeExternal methods.

Way to ignore variables 
In serialization, JVM ignores transient variable during serialization and deserialization of java object 
Programmer can write their own logic to ignore some of the variables during externalization of java object 

Performance 
In serializable interface uses reflection which causes relatively slow performance.
Externalizable gives full control over the implementation approach. 

Object serialization with inheritance 
1. If the superclass is not serializable then the subclass still can be serialized.
2. If a subclass is not serialized but superclass is automatically serializable 
We can apply this to externalizable as well.

Example of Externalizable

class ExternalizableExample implements Externalizable {
   Integer id;
   @Override
   public void writeExternal(ObjectOutput out) throws IOException {
      out.writeInt( id );
   }
   @Override
   public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
      this.id = in.readInt();
   }
}

Example of Serializable

class SerializableExample implements Serializable {
   private static final long serialVersionUID = 5081877L;
   String name;
}
raja
Published on 18-Nov-2019 11:21:16
Advertisements