inversifyjs

Why singleton pattern is safety on single thread?


While using theinversifyJS library, I saw a statement that the singleton pattern is safe because node.js is single-threaded.

How does single-threading benefit from singletons over multithreading?


Solution

  • It's hard to know what the author meant. One likely explanation is that a single thread can't race with itself when lazily initializing a singleton. In a multi-threaded environment, two threads could naively test whether the singleton has been initialized, then both could initialize it, meaning it's no longer truly a singleton. This could cause problems if initializing it has side effects.