Mon, Aug 21 2006 11:20 AM Marc Jacobi

Double check locking optimization

While I was looking for something completly different I stumbled upon the threading best practices on msdn(2).
http://msdn2.microsoft.com/en-us/library/1c9txz50.aspx

I noticed an optimization for the double check locking pattern that I use a lot. Instead of:

if (x == null)
{
    lock (lockObject)
    {
        if (x == null)
        {
            x = y;
        }
    }
}

you can also write

System.Threading.Interlocked.CompareExchange(ref x, y, null);

It performs better but is a bit less readable (in my view).
One of those "nice to know"s.

Filed under:

Leave a Comment

(required) 
(required) 
(optional)
(required) 
Please add 2 and 2 and type the answer here: