3 ms·
Doesn't D have the ability to do stuff on class initialization? Or does it not initialize classes lazily? In Java, this is how a threadsafe Singleton looks lik
by brazzy 14y ago
Doesn't D have the ability to do stuff on class initialization? Or does it not initialize classes lazily?
In Java, this is how a threadsafe Singleton looks like:
private static MySingleton instance = new MySingleton();
It will be initialized when the class is first used.
The whole double-checked locking and TLS thing is IMO a huge pointless smartassery contest in VM lawyering hinging on the eminently false premise that having singletons in a heavily multithreaded environment initialized sooner than they're used is a problem that anyone needs solved.
Whereas in reality, 90% of all applications don't need lazy loading, and for 90% of those that do, the above is lazy enough.
- spand 14y agoI think you missed a static keyword in that line of code.
- brazzy 14y agoYou're right; fixed.
- andralex 14y agoThat requires an acquire on every access, so it's generally slower.
- brazzy 14y agoNo, it doesn't. The JVM guarantees class initialization to be threadsafe (the lock is implicit), so you don't need mutual exclusion to access the reference - it's initialized before any thread could attempt to access it.