Course contentsShow
← Computer Science
Lesson 2266 of 2,87251. Design PatternsFree lesson

Singleton Thread Safety and Lazy Initialization

Handling thread-safe Singleton implementations and understanding trade-offs between eager and lazy initialization.

Singleton Thread Safety and Lazy Initialization

You'll learn how to make Singleton patterns thread-safe and understand the trade-offs between eager and lazy initialization.

The Core Problem

When multiple threads try to create a Singleton instance simultaneously, you can end up with multiple instances—defeating the entire purpose. Thread safety ensures only one instance exists even in concurrent environments.

Two Initialization Approaches

Eager Initialization creates the instance when the class loads:

class EagerSingleton:
    _instance = EagerSingleton()  # Created immediately
    
    def __new__(cls):
        return cls._instance

This is thread-safe by default (class loading is synchronized), but wastes resources if the instance is never used.

Lazy Initialization delays creation until first access:

class LazySingleton:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:  # UNSAFE in multi-threading!
            cls._instance = super().__new__(cls)
        return cls._instance

This saves resources but needs synchronization to prevent race conditions.

Making Lazy Initialization Thread-Safe

Add locking to protect the critical section:

import threading

class ThreadSafeSingleton:
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:  # Double-checked locking
                    cls._instance = super().__new__(cls)
        return cls._instance

The double-check pattern avoids locking overhead after initialization.

Trade-Offs

  • Eager: Simple, always thread-safe, but potentially wasteful
  • Lazy: Resource-efficient, but requires synchronization complexity
  • Thread-safe lazy: Best of both worlds, but slightly more complex code

Key Takeaway: Singleton thread safety requires careful synchronization in lazy initialization; choose eager initialization for simplicity or double-checked locking for lazy, thread-safe instances with minimal overhead.