I keep on running across code that uses double-checked locking, and I’m still confused as to why it’s used at all.
I initially didn’t know that double-checked locking is broken, and when I learned it, it magnified this question for me: why do people use it in the first place? Isn’t compare-and-swap better?
if (field == null)
Interlocked.CompareExchange(ref field, newValue, null);
return field;
(My question applies to both C# and Java, although the code above is for C#.)
Does double-checked locking have some sort of inherent advantage compared to atomic operations?
Well, the only advantage that comes to my mind is (the illusion of) performance: check in a non-thread-safe way, then do some locking operations to check the variable, which may be expensive. However, since double checked locking is broken in a way that precludes any firm conclusions from the non-thread-safe check, and it always smacked of premature optimization to me anyway, I would claim no, no advantage – it is an outdated pre-Java-days idiom – but would love to be corrected.
Edit: to be clear(er), I believe double checked locking is an idiom that evolved as a performance enhancement on locking and checking every time, and, roughly, is close to the same thing as a non-encapsulated compare-and-swap. I’m personally also a fan of encapsulating synchronized sections of code, though, so I think calling another operation to do the dirty work is better.