Why Double-Checked Locking is used at all?

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?

5
задан Mehrdad 23 May 2011 в 04:11
поделиться