The Singleton that was created twice
transcript
It's a Singleton. There's exactly one. Unless two callers arrive at the same moment.
First, ask: is there an instance yet? If not, create one. Two steps. A check, then a create.
Caller one asks. No instance yet. Caller two asks, before one has created anything. Also no. Both create one. Two configs. The app thinks there is only one. The last one stored wins. The first caller holds a different config.
Here's the catch. The slower the load, the wider the gap. A config read from disk is slow enough to lose this race. And a bug like this hides until production load finds it.
Make check and create one step. Take a lock, and check again once you hold it. Or let the language do it once. Java has the holder idiom. C plus plus has a function local static.
Two steps is two chances to lose. And even when it works, it's one per process, not one per system. Four workers means four singletons.
Full breakdown in the lecture.