☕ Java Advanced

What is the Singleton design pattern and how is it implemented in Java?

Answer

The Singleton pattern ensures only one instance of a class is created throughout the application's lifetime. The classic implementation: private constructor (prevents instantiation from outside), a private static field holding the single instance, and a public static method returning that instance. The thread-safe, lazily-initialized version uses double-checked locking with a volatile field: check if null outside the synchronized block, synchronize, check again inside, create if still null. The simplest thread-safe approach is the enum singleton: enum MySingleton { INSTANCE; } — it is serialization-safe, reflection-proof, and thread-safe by design. Another elegant approach is the initialization-on-demand holder pattern, which uses static inner class for lazy initialization without synchronization overhead.