Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Constructor & Singleton class

Tags:

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
{
    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
    {
        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

like image 916
GaryJL Avatar asked Jul 15 '09 14:07

GaryJL


People also ask

What is static constructor in Java?

A static constructor used to initialize static data means the specified task will execute only once throughout the program. Usually, a static constructor is automatically called when the first instance is generated, or any static member is referenced.

Can we make static constructor?

No, we cannot define a static constructor in Java, If we are trying to define a constructor with the static keyword a compile-time error will occur. In general, static means class level. A constructor will be used to assign initial values for the instance variables.

What is difference between static constructor and private constructor?

Static constructor will be called first time when the class is referenced. Static constructor is used to initialize static members of the class. In the non static class the private or public constructor will not be called. Static members will not be initialized either by private or public constructor.


2 Answers

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

like image 167
jason Avatar answered Sep 22 '22 22:09

jason


Rather than rolling your own threadsafe lazy initializer and possibly getting it wrong, I recommend reading the msdn on Lazy<T>.

https://docs.microsoft.com/en-us/dotnet/framework/performance/lazy-initialization#thread-safe-initialization

like image 42
Eric Lippert Avatar answered Sep 21 '22 22:09

Eric Lippert