Diagnose Thread-Safety Flaws in Module Singletons
Module singletons and global configuration objects accessed by multiple threads create race conditions during lazy instantiation. Double-checked locking using a class-level threading.Lock ensures thread-safe singleton initialization without inflicting overhead on subsequent reads.
import threading
class SafeSingleton:
_instance = None
_lock = threading.Lock()
@classmethod
def instance(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = cls()
return cls._instance
# Diagnose Thread-Safety Flaws in Module Singletons When multiple threads access a lazy singleton at startup (such as a database client or metrics registry), naive code often looks like this: ```python # Broken Lazy Singleton class Database: _instance = None @classmethod def get(cls): if cls._instance is None: cls._instance = Database() # Multiple threads create distinct instances! return cls._instance ``` Under heavy concurrency, 5 threads can evaluate `if cls._instance is None:` simultaneously, instantiating 5 distinct connection pools and leaking sockets. 🛑🔒 The **Double-Checked Locking** pattern provides thread-safe singletons: 1. Fast un-synchronized check: If already initialized, return immediately (zero lock overhead). 2. If not initialized, acquire the class lock. 3. Second check inside the lock: Verify another thread didn't initialize it while we were waiting for the lock. ```python import threading class SafeSingleton: _instance = None _lock = threading.Lock() def __new__(cls): if cls._instance is None: with cls._lock: if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance ``` ## Pop Quiz Why is a double-checked lock pattern faster than placing `with self._lock` on every single access? - [ ] It avoids lock acquisition overhead on subsequent reads once the singleton instance is already instantiated. - [ ] It instructs the GIL to bypass reference count increments for singleton objects. - [ ] It forces the interpreter to place the singleton on CPU hardware cache lines. - [ ] Because Python locks automatically dissolve after their initial acquisition. ## Real-World Challenge Implement `ThreadSafeSingleton` overriding `__new__` with double-checked locking. Spin up 20 concurrent threads that simultaneously call `ThreadSafeSingleton()`, recording each returned instance in a list. Assert that all 20 threads received the exact same instance in memory (`inst is first`). <details> <summary>Solution</summary> ```python import threading class ThreadSafeSingleton: _instance = None _lock = threading.Lock() def __new__(cls, *args, **kwargs): if cls._instance is None: with cls._lock: if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance # Verification collected_instances = [] def worker(): inst = ThreadSafeSingleton() collected_instances.append(inst) threads = [threading.Thread(target=worker) for _ in range(20)] for t in threads: t.start() for t in threads: t.join() assert len(collected_instances) == 20 first_instance = collected_instances[0] for other in collected_instances[1:]: assert other is first_instance, "Thread spawned a divergent singleton instance!" ``` </details>