Video in progress
Why do many people consider an enum the most reliable option for a Singleton?
A Singleton written as an enum can't be turned into a second instance through reflection or through serialization, and the JVM guarantees that. The code also fits on one line.
📖 Answer
public enum IdGenerator {
INSTANCE;
private final AtomicLong counter = new AtomicLong();
public long next() {
return counter.incrementAndGet();
}
}
long id = IdGenerator.INSTANCE.next();
A Singleton with a regular class can be broken in two ways:
- calling the private constructor with
Constructor.setAccessible(true)and creating a new object; - serializing the object and reading it back: if
readResolveisn't written, a new instance comes out.
Neither works with an enum: reflection doesn't allow calling an enum constructor, and deserialization returns the existing constant.
The limit: an enum can't inherit from another class (it can implement an interface) and it isn't lazy. In practice this is rarely a problem.
Sign up to mark studied questions and save your progress.