Java Concurrency Interview

Patterns and antipatterns question 152 of 180 mid

What is the double-checked locking antipattern really about?

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.

antipatterns singleton

Quiz yourself on Patterns and antipatterns Suggest a correction