Difference between Serializable vs Externalizable in Java - Interview Question

What is the difference between Serializable and Externalizable in Java is famous core Java interview questions and for some of them its one of those difficult Java question, which no one wants to see in Java interview. I was in that category until I read Effective Java and explored How Serialization works in Java and find out more about the Serialization process. What makes Serialization questions tricky is, Serialization as a persistence mechanism is not very popular. Many programmers prefer databases, memory-mapped files, or simple text files over Serialization. But Serialization has a distinguished advantage over these mechanisms.

Java provides a default mechanism to preserver object state and your job many times would be as simple as adding implements Serializable on any class. In this article, we will compare Serializable to Externalizable and see some common differences between Serializable vs Externalizable to tackle this Java question.

By the way, when it comes to Serialization in Java, Serializable and Externalizable is not the only option, you can also use open source third party library like Google's protobuf to serialize your objects and send it over network. In fact, Google's protobuf will give you better performance in most cases then JDK Serialization API. 



Difference between Serializable and Externalizable in Java

Here is my list of differences between Externalizable and Serializable interface in Java. These are good points to explore on the topic of Serializable and refresher before going to any Java interview.




1. Marker Interface
One of the obvious differences between Serializable and Externalizable is that Serializable is a marker interface i.e. does not contain any method but Externalizable interface contains two methods writeExternal() and readExternal().



2. Responsibility
The second difference between Serializable vs Externalizable is the responsibility of Serialization. when a class implements Serializable interface, the default Serialization process gets kicked off and that takes responsibility for serializing the superclass state. 

When any class in Java implement java.io.Externalizable then it's your responsibility to implement the Serialization process i.e. preserving all important information.

Difference between Serializable and Externalizable interface in Java



3. Performance
This difference between Serializable and Externalizable is performance. You can not do much to improve the performance of the default serialization process except reducing number of fields to be serialized by using transient and static keywords but with an Externalizable interface, you have full control over the Serialization process.


4. Maintenance
Another important difference between Serializable and Externalizable interface is maintenance. When your Java class implements Serializable interface it's tied with default representation which is fragile and easily breakable if the structure of the class changes e.g. adding or removing a field. By using java.io.Externalizable interface you can create your own custom binary format for your object.


5. Serializable and Externalizable interface Example in Java

Here is an example of how you can use Serializable interface in Java with your class

import java.io.Serializable;

public class Book implements Serializable {

    private static final long serialVersionUID = 1L;
    private String author;
    private String title;
    private int numberOfPages;

    // getters and setters
}

In above example, Book class implement Serializble interface which means you can convert object of Book class into byte stream and send it across network or save into file. It also means that, you can also convert a byte stream back to Book object. 

The SerialVersionUID is a unique identifier which is used by JDK's serialization API to ensure that the version which is de-serialized (converted back to Object) is compatible with the version which was serialized. If they are not compatible then you cannot convert them and you will get error like Not compatible. 

Now, let's see an example of Externalizable interface in Java:

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class Book implements Externalizable {

    private String author;
    private String title;
    private int price;

    public Book() {}

    public Book(String author, String title, int price) {
        this.author = author;
        this.title = title;
        this.price = price;
    }


    // getters and setters


    @Override
    public void writeExternal(ObjectOutputStream out) throws IOException {
        out.writeObject(author);
        out.writeObject(title);
        out.writeInt(price);
    }


    @Override
    public void readExternal(ObjectInputStream in) throws IOException, 
                                          ClassNotFoundException {
        this.author = (String) in.readObject();
        this.title = (String) in.readObject();
        this.price = in.readInt();
    }
}

In the above example, our Book implement Externalizable interface which is a sub-interface of Serializable and it provides more fine-grained control of how your object is serialized or converted into byte stream. 

Serializable vs Externalizable in Java DifferenceInstead of using default serialization mechanism, Externalizable interface provides you writeExternal(ObjectInput out) and readExterna(ObjectInput in) method to code your own logic for serialization and de-serialization.  

The writeExternal() method is used to write object's state into ObjectOutputStream and read object state from ObjectInputStream class. 


That's all guys. these are some of the important differences between the Serializable vs Externalizable interfaces in Java. It's even better if you try to write a Java program one with Serializable interface and other implementing the Externalizable interface. Then you can evaluate all these differences between them. 

It's also worth noting that by implementing Serializable and Externalizable interface your Class become stateful and it may not be suitable in a Microservice architecture where stateless object are preferred as stateful object can cause problems in caching, replication, and scaling. 


4 comments:

  1. 4th point is really good

    ReplyDelete
  2. You might like to reference http://javarevisited.blogspot.com/2012/01/serializable-externalizable-in-java.html as your original posting.

    ReplyDelete
  3. Externalization interface allows you to define your own binary protocol for Serialization. But you can also customize customize serialization process you implement readObject() and writeObject() method from java.io.Externalizable interface. JVM checks implementation of these methods and call them instead of usual one .

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.