3 ms·
In modern Java, it's easy enough if you've been shown the pattern. What's hard is understanding/discovering it from first principles.
by hyperpape 11y ago
In modern Java, it's easy enough if you've been shown the pattern. What's hard is understanding/discovering it from first principles.
- hyperpape 11y agoSomeone apparently disliked this comment, but check out http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLo.... Scroll down to "Fixing Double-Checked Locking using Volatile." It's five lines of code without braces, and can be applied without any creativity or reasoning.
- cryon 11y agoYou should use enums for singletons i Java. Simple to write, threadsafe and handles serialization. All with guarantees from the Java language specification.
- hyperpape 11y agoI wasn't actually talking about singletons, just the doublechecked locking pattern. It's also necessary for laziness on objects that are referenced by multiple threads. I tend to think Singletons are a dubious design pattern, like a lot of other people.