Video in progress
Why is a singleton written as an enum more resistant to reflection and serialization?
The JVM creates an enum constant exactly once and doesn't allow any other creation: Constructor.newInstance fails on an enum, and deserialization returns that very constant by name.
📖 Answer
An ordinary singleton can be "broken" in two ways:
// 1) Reflection
Constructor<Config> c = Config.class.getDeclaredConstructor();
c.setAccessible(true);
Config second = c.newInstance(); // a second instance
// 2) Serialization
Config copy = (Config) in.readObject(); // another new instance
Against the second you write readResolve(), and against the first a flag check in the constructor. Both are manual, and both are easy to forget.
With an enum:
public enum Config {
INSTANCE;
private final Properties props = load();
public String get(String k) { return props.getProperty(k); }
}
newInstancethrowsIllegalArgumentException: Cannot reflectively create enum objectsfor an enum;- on serialization an enum writes only its name, and on reading it calls
Enum.valueOf; - class loading is thread-safe, so even lazy init doesn't need double-checked locking.
The downside: an enum can't extend another class, and initialization happens when the class is loaded.
In a real project, though, a singleton is usually managed by the DI container (a Spring bean is a singleton by default), and a static singleton makes tests harder to write. An enum singleton is good for a library or for places without DI.
Sign up to mark studied questions and save your progress.