Patterns and antipatterns question 152 of 180 mid
What is the double-checked locking antipattern really about?
- It is always wrong
- Correct: It is correct only with a volatile field, and for most cases there is a simpler construct that avoids it entirely
- It is a performance optimisation with no correctness issue
- It only works in a single-threaded program
The idiom exists to avoid taking a lock on every read of a lazily initialised field. Without volatile
it is broken, because another thread can see a published reference to a partially constructed object.
With volatile it is correct.
The better answer is to avoid needing it. For a static singleton, the holder idiom relies on the JVM's
class initialisation lock and needs no volatile, no synchronized and no double check. For an instance
field, AtomicReference with compareAndSet or Suppliers.memoize-style wrapping says what you mean.
And eager initialisation is usually fine: the object is almost always cheaper than the argument about
it.
Interviewers ask this to see if you reach for the clever construct or for the simple one.
Quiz yourself on Patterns and antipatterns Suggest a correction