Video in progress

Strong Middle 📁 IO and NIO

Why does a Serializable singleton turn into a second instance after deserialization, and how do you stop that?

Deserialization creates a new object every time, bypassing even the private constructor. With readResolve() you return the existing instance instead of the new object. The most reliable way is to make the singleton an enum.

📖 Answer

class AppClock implements Serializable {
    static final AppClock INSTANCE = new AppClock();
    private AppClock() {}
}

byte[] bytes = serialize(AppClock.INSTANCE);
AppClock copy = (AppClock) deserialize(bytes);
System.out.println(copy == AppClock.INSTANCE); // false

Now there are two "single" objects in the system. If it has state (a counter, a cache), they drift apart.

readResolve is called after the object is read from the stream, and the value it returns is given as the result:

@Serial
private Object readResolve() {
    return INSTANCE;
}

There is a catch: the deserialized copy is still created temporarily. If the class has serializable fields of a reference type, a cleverly crafted stream can capture a reference to that inner object before readResolve runs; Effective Java describes this attack in detail. So make such fields transient.

With an enum, all of these problems are gone: for an enum, serialization writes only the name and on reading the same constant comes back through valueOf. You can't create a new instance of an enum even with reflection.