Recently I was having a chat with someone about the Singleton pattern and we were looking at a standard implementation, which looks something like this

public class Loner
{
    private Loner() { }
    private static Loner _Instance;
    public static Loner Instance
    {
        get
        {
            if (_Instance == null)
            {
                _Instance = new Loner();
            }
            return _Instance;
        }
    }
}

To get the Singleton instance you would call Loner.Instance. Now, do you see the problem? No, neither did I to start off with, until the guy I was chatting to asked what would happen if many threads called Loner.Instance at the same time.

Ahhh, light dawns. That's right; this implementation is not thread safe, if two or more threads arrive at the null test at the same time, you may get two or more "singleton" instances being created. Obviously, this breaks the pattern and is not good. We could fix this by inserting a mutex around the test and instance creation, in C# this is done by using a lock, like so

public class Loner
{
    private Loner() { }
    private static Loner _Instance;
    public static Loner Instance
    {
        get
        {
            lock (typeof(Loner))
            {
                if (_Instance == null)
                {
                    _Instance = new Loner();
                }
            }
            return _Instance;
        }
    }
}

Now, whilst this would work, and is indeed thread safe, the thing is locks are expensive and if you have many threads running this code, you may see a performance hit. Perhaps a better solution is this

public class Loner
{
    private Loner() { }
    private static Loner _Instance = new Loner();
    public static Loner Instance
    {
        get { return _Instance; }
    }
}

This is both thread safe and does not have the overhead of a lock.

Technorati tags: , ,