Creational PatternBEGINNER6 min deep dive

Singleton Pattern Pattern

Ensures a class has only one instance and provides a global point of access to it.

Real-World Mental Model / Metaphor:

The President of a country: there can only be one official president at any given time, accessible to all government departments.

Interactive Runtime Simulator

Test and tweak inputs dynamically

Interactive Singleton Pattern SimulatorLIVE PLAYGROUND

Interact with the controls below to see how this design pattern executes in memory at runtime.

Category: Creational
Multithreaded Singleton Test:

Click the button below to spawn 5 concurrent simulated worker threads simultaneously calling DatabasePool.getInstance().

Double-Checked Locking Guard:

Uses volatile to prevent JVM instruction reordering and double synchronization checks to guarantee zero race conditions during instance creation.

CONCURRENT THREAD TRACE1 Shared Instance
Click “Spawn 5 Concurrent Threads” to test thread safety.
The Problem It Solves

Multiple parts of an application creating competing instances of a shared resource (like database connection pool or logger file lock), causing conflicts.

The Architectural Solution

Private constructor + static variable holding the instance + public thread-safe `getInstance()` method.

Pattern Structure & Participants

ParticipantRole & ResponsibilityType
Singleton ClassHas private constructor and private static instanceclass
getInstance()Thread-safe accessor (Double-checked locking or Bill Pugh)class
Collaboration Rules:
  • Constructor is private
  • Clients invoke Singleton.getInstance() to retrieve the shared instance

Production Code Implementation

Singleton Pattern.java
// 1. Thread-Safe Double-Checked Locking (Optimized for performance)
public class DatabaseConnectionPool {
    // volatile prevents instruction reordering in multithreaded JVM
    private static volatile DatabaseConnectionPool instance;

    private DatabaseConnectionPool() {
        // Prevent reflection instantiation attack
        if (instance != null) {
            throw new IllegalStateException("Already instantiated!");
        }
    }

    public static DatabaseConnectionPool getInstance() {
        if (instance == null) { // First check (no locking overhead)
            synchronized (DatabaseConnectionPool.class) {
                if (instance == null) { // Second check (synchronized)
                    instance = new DatabaseConnectionPool();
                }
            }
        }
        return instance;
    }
}

// 2. Bill Pugh Singleton (Lazy initialization via static inner class)
public class BillPughSingleton {
    private BillPughSingleton() {}

    private static class HelperHolder {
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance() {
        return HelperHolder.INSTANCE; // Loaded on-demand when called
    }
}
When to Use:
  • •When exactly one instance of a class is needed to coordinate actions across the system (e.g. database pool, cache manager, audio driver).
  • •When strict control over global variables is needed.
When to Avoid (Anti-Pattern):
  • •As a lazy replacement for passing parameters (turns into an anti-pattern).
  • •In unit tests when mockability and test isolation are critical (singletons introduce global state).

Staff Engineering Interview Insights & Gotchas

  • Always explain why `volatile` is mandatory in Double-Checked Locking (prevents instruction reordering).
  • Know the Enum Singleton (Josh Bloch pattern) as the cleanest reflection-proof and serialization-safe implementation in Java.