views:

486

answers:

3

I have an object cache which implements the Singleton design pattern. My approach to singleton was always to lazy load the static instance when the property is first accessed.

public static Widget Instance
{
    get
    {
        if(instance==null) instance = new Widget();
        return instance;
    }
}

However, I know that this approach isn't thread safe and the check for instance being null introduces a small inefficiency. Would it be wise to implement a static constructor on the class which instantiates the static instance?

As I understand it, the static constructor would be called whenever the first static property access occurs. Is this valid, and will it provide any benefits over the current lazy load approach or would it be better to explore a proxy implementation, or use a lock to force it to be thread safe?

public static Widget Instance
    {
        get
        {
            if(instance==null)
            {
                lock(padlock)
                {
                    if(instance==null) instance = new Widget();
                }
            }
            return instance;
        }
    }

I don't have a whole lot of experience with static constructors, so don't want to leap in with this idea if it is an equal or worse implementation of the lazy load property.

Cheers, Gary

+9  A: 

Jon Skeet has a nice article on singletons discussing this issue.

Jason
Perfect - His Fourth implementation was exactly what I was after. Thanks!
GaryJL
Jon Skeet should be in here to soak up some rep for his own article :-D
frou
Jon recently hit 100k... I'm not sure there's any place even left to soak :)
Pavel Minaev
This works well with IOC containers too: http://www.tavaresstudios.com/Blog/post/Resolving-a-Singleton-Heres-how.aspx
Mike Post
+2  A: 

Rather than rolling your own threadsafe lazy initializer and possibly getting it wrong, I recommend simply using Joe Duffy's lazy initializer class.

http://www.bluebytesoftware.com/blog/PermaLink,guid,a2787ef6-ade6-4818-846a-2b2fd8bb752b.aspx

Eric Lippert
A: 

I usually make a singleton this way: http://www.vikingworks.dk/page/Creating-a-Singleton-Pattern-i-C.aspx which is similary to Jon Skeets implementationexcept with a twist on replacing the instance, inspired by Fowlers registry pattern.

H4mm3rHead