Video in progress
In what situations does a classic Singleton still end up as two or more instances?
Uniqueness is only guaranteed within a single classloader. Different classloaders (an app server, hot reload, a plugin system), serialization without readResolve, reflection and a cluster (several JVMs): each of these produces a second instance.
📖 Answer
The idea that "a Singleton is one per whole program" is wrong. The real cases:
Classloaders. A static field belongs to a class, and a class is identified by the pair (name + classloader). In Tomcat, if two WARs bring the same library in their own WEB-INF/lib, each has its own Config.INSTANCE. Spring Boot DevTools has a restart classloader: some classes are reloaded and some aren't, and ClassCastException: Config cannot be cast to Config comes from exactly that.
Serialization.
public class Settings implements Serializable {
public static final Settings INSTANCE = new Settings();
private Settings() {}
private Object readResolve() { return INSTANCE; } // without it a new instance comes out
}
Reflection. getDeclaredConstructor().setAccessible(true) calls the private constructor. A check inside the constructor ("throw if already created") gives partial protection. An enum is fully resistant to this.
Cloning. If it inherits from a parent class that implements Cloneable, you need to override clone() and throw an exception.
Several JVMs. The one people forget most. In Kubernetes, 3 pods means 3 "singletons". If the Singleton holds an in-memory counter, a rate limiter or a scheduler that's "supposed to run in only one place", it silently misbehaves when you scale horizontally. If you need uniqueness across the cluster, use a database lock (ShedLock), Redis, or leader election.
In an interview, mentioning this last point usually earns the most points, because it's a real prod problem.
Sign up to mark studied questions and save your progress.