Java
Serializable
Externalizable
Programming
Java Serialization

What is the difference between Serializable and Externalizable in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Java, serialization is the process of converting an object into a byte stream, enabling the encoded object to be easily saved to persistent storage or transmitted over a network. Deserialization, conversely, involves reconstructing an object from these bytes. Java provides two main interfaces to handle serialization: Serializable and Externalizable. Both are used for different purposes depending on the requirements of the system.

Serializable Interface

The Serializable interface is a marker interface, which means it does not contain any methods. When a class implements this interface, it is signaling to the Java Virtual Machine (JVM) that its instances can be serialized automatically. Serialization with Serializable is predominantly controlled by the JVM, which decides how the objects are converted into a series of bytes. This includes the object's data (fields and members), as well as some metadata about the object's type and the types of its fields.

For more control over serialization, a class implementing Serializable can optionally define two methods (writeObject and readObject), which allow custom behavior during serialization and deserialization. These methods must be implemented as private to ensure that they cannot be overridden or accessed externally. Custom serialization can be used, for example, to obfuscate sensitive information or reduce the size of the object to be saved.

java
1public class User implements Serializable {
2    private static final long serialVersionUID = 1L;
3    
4    private String name;
5    transient private String password; // This field will not be serialized
6
7    private void writeObject(ObjectOutputStream oos) throws IOException {
8        oos.defaultWriteObject(); // Serialize the non-transient fields
9        // Custom serialization for 'password'
10    }
11
12    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
13        ois.defaultReadObject(); // Deserialize the non-transient fields
14        // Custom deserialization for 'password'
15    }
16}

Externalizable Interface

The Externalizable interface extends Serializable and adds two methods: writeExternal and readExternal. Unlike Serializable, where serialization is primarily JVM-controlled, Externalizable grants complete control over the serialization process to the programmer.

When using Externalizable, developers must implement these two methods to explicitly specify not only the data to serialize but the exact format and process of serialization and deserialization. This approach provides the flexibility to programmatically decide which object fields are serialized and in what format, potentially leading to performance optimizations and enhanced security features.

java
1public class User implements Externalizable {
2    
3    private String name;
4    private String email;
5
6    @Override
7    public void writeExternal(ObjectOutput out) throws IOException {
8        out.writeObject(name);
9        out.writeObject(email);
10    }
11
12    @Override
13    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
14        name = (String) in.readObject();
15        email = (String) in.readObject();
16    }
17}

Comparison and Uses

The choice between Serializable and Externalizable is critical and depends on specific use cases:

  • Performance: Externalizable can often be more performant since it allows for customized serialization logic which might be tuned for specific use cases.
  • Flexibility & Control: With Externalizable, the developer assumes total control over the serialization process, which can be powerful but also adds more complexity and responsibility.
  • Ease of Implementation: Implementing Serializable is generally simpler and quicker since it requires minimal code changes. Externalizable requires more boilerplate as the developer must manually handle the serialization details.

Here is a quick summary of the key differences:

FeatureSerializableExternalizable
Interface TypeMarker InterfaceFunctional Interface
Method ImplementationNot requiredRequired (writeExternal, readExternal)
Control Over ProcessJVM ControlledDeveloper Controlled
Use CaseGeneral UsageAdvanced Scenarios for Performance and Control

Conclusion

In conclusion, Serializable and Externalizable provide two mechanisms for object serialization in Java, each suited to different needs and scenarios. Serializable offers a quick and straightforward approach, often sufficient for general purposes. In contrast, Externalizable provides detailed control and optimization capabilities, ideal for scenarios where performance and specific serialization behaviors are required.


Course illustration
Course illustration

All Rights Reserved.