A junior developer writes a class 'Logger' that should only ever have one instance (singleton). They attempt to implement it by overriding __new__ to always return the same instance. However, when multiple threads attempt to create a Logger, they sometimes get different instances. Which modification will make the singleton thread-safe?
Acquiring a threading.Lock inside __new__ before checking and assigning the class-level singleton reference serializes the critical section, so concurrent threads cannot both observe a None value and proceed to construct separate instances. Without this lock, even with CPython's GIL, a thread can be suspended between the check and the assignment, allowing another thread to create a second instance. This approach directly addresses the race condition at the point where the object is actually allocated and published.
Why this answer
The race condition occurs when multiple threads simultaneously check `cls._instance` and find it `None`, then both proceed to create a new instance. Wrapping the creation logic inside a `threading.Lock` in `__new__` ensures that only one thread can execute the critical section at a time, guaranteeing that only one instance is ever created.
Exam trap
Python Institute often tests the misconception that simply overriding `__new__` or using a class method is sufficient for thread safety, when in fact the race condition in the check-then-create pattern requires explicit synchronization like a lock.
How to eliminate wrong answers
Option B is wrong because calling a class method from `__init__` does not prevent the race condition; `__init__` is still called on every instantiation attempt, and the check-then-create pattern in the class method is itself not thread-safe without a lock. Option C is wrong because a metaclass overriding `__call__` can implement a singleton, but it does not inherently provide thread safety unless the metaclass itself uses a lock or other synchronization mechanism. Option D is wrong because overriding `__init__` to skip initialization does not prevent multiple instances from being created; `__new__` still returns a new object each time, and the singleton pattern requires controlling instance creation, not just initialization.