Exercise 2: Why the Race Condition Only Happens on First Access — Possible Solution ==================================================================== WHERE THE ACTUAL RACE WINDOW IS ------------------------------ This chapter's own naive Singleton has exactly one dangerous moment: the gap between checking "if cls._instance is None" and actually finishing the assignment "cls._instance = super().__new__(cls)". Verified directly, this chapter's own test even inserted an artificial delay specifically inside that gap to make the race easier to trigger, and the result was 8 distinct instances from 20 threads. WHY MULTIPLE FIRST-TIME CALLERS ARE SPECIFICALLY WHAT TRIGGERS IT ------------------------------ The dangerous gap only exists while cls._instance still equals None - once ANY thread successfully finishes creating the instance and assigns it to cls._instance, every subsequent check of "cls._instance is None" evaluates to False immediately, and no thread can enter that dangerous creation branch again. The race condition this chapter measured therefore can only happen among the threads that happen to all check cls._instance while it is STILL None - which is only possible before the very first successful creation completes. Once that first creation genuinely finishes, the unsafe branch of code becomes permanently unreachable for the rest of the program's lifetime. WHY LATER CONCURRENT ACCESS TO AN ALREADY-INITIALIZED SINGLETON IS SAFE ------------------------------ If multiple threads call the Singleton constructor AFTER the instance already exists, every one of them evaluates "cls._instance is None" as False and simply returns the existing cls._instance directly - reading an already-set reference to an existing object is not the kind of operation that creates or corrupts an instance, so there is no creation logic left to race on. This is exactly why this chapter's own thread-safe fix only needed to protect the CREATION path specifically (the double-checked locking around cls._instance = ...) rather than needing to guard every single future access to the Singleton for the rest of the program's execution. WHY THIS WORKS AS AN ANSWER ------------------------------ The explanation identifies the precise code region where the race is possible (the gap between the None-check and the assignment), explains why that gap can only ever be exploited before the first successful creation completes, and correctly distinguishes CREATING the instance (dangerous while uninitialized) from merely READING an already-created instance (always safe), grounding the argument in this chapter's own verified 8-instances-from-20-threads result.