HowTo: Thread safe singleton implementation of a class

Normally, if you would like a singleton implementation of a class, you would go about it a little bit like this:

public class BloggingAbout
{
   
private static BloggingAbout bloggingAbout;
   
    private BloggingAbout()
    {
    }

    public static BloggingAbout BloggingAboutInstance
    {
        get
       
{
            if (bloggingAbout == null)
            {
                bloggingAbout = new BloggingAbout();
            }
            return bloggingAbout;
        }
    }
}

The trouble here is that this implementation is not thread safe. The reason I post this is I recently ran into some code of an old colleague of mine (from my former employee) and some tests showed his singleton class was instantiated several times when the application was stressed with requests from the start, which caused unwanted lag in the application. Apparently him not implementing the Singleton pattern thread safe caused this, so I fixed it.
It's not thread safe because two different threads could both evaluate if (bloggingAbout == nulland find it to be true and create an instance, which violates the singleton pattern. To make sure this doesn't happen, you could use locking which would result in this code:

public class BloggingAbout
{
   
private static BloggingAbout bloggingAbout;
    private static object lockObject = new object();
    
    private BloggingAbout()
    {
    }

    public static BloggingAbout BloggingAboutInstance
    {
        get
       
{
            lock(lockObject)
            {

                if (bloggingAbout == null)
                {
                    bloggingAbout = new BloggingAbout();
                }
                return bloggingAbout;
            }
        }
    }
}

The lock statement ensures that one thread does not enter a critical section of code while another thread is in that critical section. If another thread attempts to enter a locked section of code, it will wait (block) until the object is released. This is the reason the lockObject has to exist even before calling the static property BloggingAboutInstance.

Published Wed, Sep 21 2005 10:59 PM by Rick van den Bosch
Filed under: ,

Comments

# re: HowTo: Thread safe singleton implementation of a class

Have a look at Brad Adams post on singletons, locking and volatile (http://blogs.msdn.com/brada/archive/2004/05/12/130935.aspx)

this starts with 'the best practice' on this subject (double check locking pattern) and he factores the volatile keyword out. Whether that is necessery, I leave up to others.

but I think 'double checking' around your lock it worth your while. This way you won't lock while accessing an created instance of your static instance.

Wednesday, September 21, 2005 2:48 PM by Olaf Conijn

# re: HowTo: Thread safe singleton implementation of a class

Why not doing it this way:

public sealed class Singleton
{
static readonly Singleton instance=new Singleton();

static Singleton()
{
}

Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}

Wednesday, September 21, 2005 11:39 PM by P.J. van de Sande

# re: HowTo: Thread safe singleton implementation of a class

I doubt if the last sample provide thread safe access. The il will at least submit 3 statements, a call to .ctor, a pop and a ld. After the call to the .ctor a context switch might take place. That will allow the second thread to call into the Instance property again.

Saturday, September 24, 2005 3:25 AM by rene

# re: HowTo: Thread safe singleton implementation of a class

You must provide the STATIC Ctor, otherwise the compiler will mark it as beforefieldinit.

Tuesday, September 27, 2005 12:02 PM by P.J. van de Sande

Leave a Comment

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