Video in progress

What is the difference between Externalizable and Serializable?

With Serializable the JVM writes all the fields itself using reflection. With Externalizable you fully control what is written and how in the writeExternal and readExternal methods; the class must have a public no-argument constructor.

📖 Answer

public class Money implements Externalizable {
    private long amountTiyin;
    private String currency;

    public Money() {}  // required: deserialization creates the object through it

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeLong(amountTiyin);
        out.writeUTF(currency);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException {
        amountTiyin = in.readLong();
        currency = in.readUTF();
    }
}

The differences in practice:

  • Externalizable writes less metadata and uses no reflection, so the output can be smaller and faster;
  • the read order has to match the write order exactly, otherwise you silently get corrupted data;
  • versioning is entirely on you;
  • the parent class's fields are lost unless you write them yourself.

Serializable has a middle path too: add private writeObject/readObject methods, keep the default writing (defaultWriteObject) and change only certain parts. In most cases that is enough.

Today Externalizable is rare; you find it more in old cache libraries or in code written for performance.