The readResolve Method for Singleton Protection
What you'll learn: How to use readResolve() to prevent deserialization from breaking the singleton pattern.
The Problem with Singletons and Serialization
When you make a singleton class Serializable, deserialization creates a new instance every time you read the object from a stream—completely defeating the singleton pattern! Java's deserialization mechanism bypasses constructors, so your carefully controlled getInstance() method can't prevent this.
Analogy: Imagine you have one master key to a building (your singleton). When someone photocopies that key (deserializes), they get a functional duplicate—now you have two "master" keys, which breaks your security model.
How readResolve Fixes This
The readResolve() method gives you a hook to replace the deserialized object with the correct singleton instance. After deserialization constructs the object, Java checks if readResolve() exists and returns its result instead.
Method signature:
private Object readResolve() {
return INSTANCE; // Return the singleton instance
}
Example: Protecting a Singleton
public class DatabaseConnection implements Serializable {
private static final long serialVersionUID = 1L;
private static final DatabaseConnection INSTANCE = new DatabaseConnection();
private DatabaseConnection() {
// Private constructor
}
public static DatabaseConnection getInstance() {
return INSTANCE;
}
// Protect singleton during deserialization
private Object readResolve() {
return INSTANCE;
}
}
Now when you deserialize, the temporary object is discarded and INSTANCE is returned—preserving the singleton guarantee.
Why It Works
After readObject() reconstructs the object, Java invokes readResolve() if present. The returned object becomes the final result of deserialization, and the reconstructed object is garbage-collected.
Key Takeaway: Always implement readResolve() returning your singleton instance in serializable singletons to prevent deserialization from creating duplicate instances and breaking the singleton contract.