What are the different ways to design a thread-safe Singleton in Java?
There are three commonly used correct approaches. Eager initialization declares the instance as private static final Singleton INSTANCE = new Singleton(); this relies on the JVM's class-loading process being inherently thread-safe, and while it's simple, it always creates the instance at class-load time even if it's never actually used. Double-checked locking checks for null, enters a synchronized block, checks null again inside the lock, and only then constructs the instance; the instance field must be declared volatile, since without it the JVM could reorder construction and expose a partially built object to another thread. The best of the three is usually the initialization-on-demand holder idiom: a private static nested class holds the instance as a static final field, so the instance is only created the first time the holder class is actually loaded, giving lazy initialization with no explicit synchronization needed at access time, guaranteed thread-safe purely by the class-loading mechanism. Java enums also provide an easy, inherently thread-safe way to implement a singleton.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response