1. Introduction

The Singleton pattern is one of the most widely used design patterns in software development. It ensures that a class has only one instance throughout the application lifecycle and provides global access to that instance.

Common use cases for the Singleton pattern include:

  • Database connection pools that manage limited database connections efficiently
  • Logger instances that centralize logging functionality across an application
  • Configuration managers that store application-wide settings
  • Cache managers that maintain shared data across multiple components
  • Thread pools that manage worker threads for concurrent operations

However, when implementing the Singleton pattern in multi-threaded environments, things quickly become more complex. Without proper thread-safety guarantees, multiple threads may simultaneously create separate instances, breaking the core promise of Singleton and potentially leading to resource conflicts or inconsistent state. This can lead to resource conflicts, inconsistent state, and unpredictable application behavior.

In this guide, we’ll explore various approaches to implement thread-safe Singleton patterns in Java, examining their trade-offs and best practices.

2. The Classic Problem with Singleton

Let’s start by examining why the basic lazy-initialized Singleton implementation fails in multi-threaded environments.

Here’s a typical non-thread-safe Singleton implementation:

This implementation works perfectly in single-threaded applications. However, in multi-threaded environments, a race condition can occur:

  1. Thread A calls getInstance() and finds instance is null
  2. Thread B calls getInstance() simultaneously and finds instance is null
  3. Both threads proceed to create new instances
  4. The application now has instantiated multiple Singleton instances, violating the pattern

Let’s demonstrate this with a test that exposes the race condition using CountDownLatch, which will help us to run the threads in parallel:

This test demonstrates how concurrent access can create multiple instances, breaking the Singleton contract. In a proper Singleton, instances should be 1. But due to race conditions, we might get multiple instances.

3. Synchronized Accessor: Simple and Safe

We can make the getInstance() method synchronized:

public static synchronized SynchronizedSingleton getInstance() { ... }

This guarantees mutual exclusion but introduces performance overhead, as synchronization happens on every access

@Test
void givenMultipleThreads_whenUsingSynchronizedSingleton_thenOnlyOneInstanceCreated() {
    Set<Object> instances = ConcurrentHashMap.newKeySet();
    IntStream.range(0, 100).parallel().forEach(i ->
      instances.add(SynchronizedSingleton.getInstance()));
    assertEquals(1, instances.size());
}

This approach is straightforward and effective in low-concurrency scenarios or cases where singleton creation is rarely accessed.

4. Eager Initialization: Thread Safety by Class Loading

An eager Singleton uses static field initialization:

private static final EagerSingleton INSTANCE = new EagerSingleton();

It’s inherently thread-safe, as the JVM guarantees class initialization is atomic. The downside? The instance is created even if never used, which may not be optimal for expensive resources:

@Test
void whenCallingEagerSingleton_thenSameInstanceReturned() {
    assertSame(EagerSingleton.getInstance(), EagerSingleton.getInstance());
}

This pattern is ideal when the singleton is guaranteed to be needed at startup.

5. Double-Checked Locking (DCL): Lazy and Efficient

DCL combines lazy initialization with reduced synchronization:

if (instance == null) {
    synchronized (...) {
        if (instance == null) {
            instance = new Singleton();
        }
    }
}

This pattern is both lazy and thread-safe, but requires the instance variable to be declared volatile

@Test
void givenDCLSingleton_whenAccessedFromThreads_thenOneInstanceCreated() {
    List<Object> instances = Collections.synchronizedList(new ArrayList<>());
    IntStream.range(0, 100).parallel().forEach(i ->
      instances.add(DoubleCheckedSingleton.getInstance()));
    assertEquals(1, new HashSet<>(instances).size());
}

This approach improves performance by avoiding synchronization once the instance is initialized. The volatile keyword ensures visibility of changes across threads. It has a good use case for high-concurrency environments where performance matters.

6. Bill Pugh Singleton: Lazy and Elegant

Bill Pugh Singleton technique uses a static inner class:

public class BillPughSingleton {
    private BillPughSingleton() {
    }

    private static class SingletonHelper {
        private static final BillPughSingleton BILL_PUGH_SINGLETON_INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance() {
        return SingletonHelper.BILL_PUGH_SINGLETON_INSTANCE;
    }
}

The class remains unloaded until the system references it, which ensures both laziness and thread safety without synchronization:

@Test
void testThreadSafety() throws InterruptedException {
    int numberOfThreads = 10;
    CountDownLatch latch = new CountDownLatch(numberOfThreads);
    Set<BillPughSingleton> instances = ConcurrentHashMap.newKeySet();

    for (int i = 0; i < numberOfThreads; i++) {
        new Thread(() -> {
            instances.add(BillPughSingleton.getInstance());
            latch.countDown();
        }).start();
    }

    latch.await(5, TimeUnit.SECONDS);

    assertEquals(1, instances.size(), "All threads should get the same instance");
}

7. Enum Singleton: The Simplest Thread-Safe Singleton

Enums provide a robust Singleton solution. The JVM instantiates enum values only once:

public enum EnumSingleton {
    INSTANCE;

    public void performOperation() {
        // Singleton operations here
    }
}

Java instantiates enum constants only once when it loads the enum, ensuring they are inherently thread-safe:

@Test
void givenEnumSingleton_whenAccessedConcurrently_thenSingleInstanceCreated()
  throws InterruptedException {
    Set<EnumSingleton> instances = ConcurrentHashMap.newKeySet();
    CountDownLatch latch = new CountDownLatch(100);

    for (int i = 0; i < 100; i++) {
        new Thread(() -> {
            instances.add(EnumSingleton.INSTANCE);
            latch.countDown();
        }).start();
    }

    latch.await();
    assertEquals(1, instances.size());
}

It’s also serialization-safe and reflection-safe.

8. Conclusion

Thread safety in Singleton implementations is critical in concurrent Java applications. While synchronized methods are simple to implement, they come at a cost—they don’t scale well under high concurrency. The best options today include:

  • Bill Pugh Singleton for most use cases
  • Double-Checked Locking for performance-critical lazy initialization
  • Enum Singleton for simplicity and safety

Each method solves the same problem with different trade-offs. Choose the one that best fits your application’s requirements. As always, the full source code and tests are available over on GitHub.