Thread safety in static methods and variables

I was under the impression that static initialization is thread safe by default. Is that correct? Also consider the below example of singleton pattern.

public sealed class SingletonDemo
{
    private static readonly SingletonDemo instance = new SingletonDemo();    
    private SingletonDemo()
    {}
    public static SingletonDemo Instance
    {
        get
        {
            return instance;
        }
    }
} 

Is above example thread safe? If yes why? If No why?

Jon Skeet
people
quotationmark

I was under the impression that static initialization is thread safe by default. Is that correct?

Yes, in terms of initialization - unless you use reflection to call the type initializer again, etc. Of course, there can then be multiple threads accessing the singleton at a time, so you need to make sure that instance members are thread-safe.

Note that with C# 6, the code can be simplified to:

public sealed class SingletonDemo
{
    public static SingletonDemo Instance { get; } = new SingletonDemo();    
    private SingletonDemo() {}
}

The type initialization rules of the CLR ensure that:

  • The type is only initialized once
  • While the type is being initialized in one thread, other threads trying to access it block
  • There is a memory barrier after type initialization is completed, so any threads accessing the variable after type initialization has completed will see the right value

With the code as it is, laziness is not guaranteed - in other words, SingletonDemo may be initialized even if it's never actually used (e.g. because a method is called which conditionally uses it, but the condition isn't hit). To make it fully lazy, you could either use Lazy<T> or a static initializer:

public sealed class SingletonDemo
{
    public static SingletonDemo Instance { get; } = new SingletonDemo();    
    private SingletonDemo() {}
    private static SingletonDemo() {}
}

people

See more on this question at Stackoverflow