Double-Checked Locking

Synchronization Pattern

A concurrency pattern which reduces the overhead of acquiring a lock. First, the locking condition is tested without acquiring the lock. Only if this check indicates that locking is required the actual locking mechanism and the synchronized logic is executed.

Sample implementation in C# (.NET 2.0+):

public class MySingleton 
{
    private readonly object _lock = new object();
    private MySingleton _singleton;

    public static MySingleton GetInstance()
    {
        get
        {
            if (_singleton == null)
            {
                lock (_lock)
                {
                    if (_singleton == null)
                        _singleton = new MySingleton();
                }
            }
            return _singleton;
        }
    }
}

Links