1

I've been going through the singleton pattern, but I'm not understanding how the below code is thread safe:

public class ThreadSafeSingleton
{
    private ThreadSafeSingleton()
    {
    }

    public static ThreadSafeSingleton Instance
    {
        get { return Nested.instance; }
    }

    private class Nested
    {
        static Nested()
        {
        }

        internal static readonly ThreadSafeSingleton instance = new ThreadSafeSingleton();
    }
}

Why is this thread-safe?

halfer
  • 19,824
  • 17
  • 99
  • 186
loop
  • 9,002
  • 10
  • 40
  • 76
  • 2
    Jon Skeet discusses this here http://csharpindepth.com/articles/general/singleton.aspx – kenny Mar 29 '15 at 13:59
  • Note this is the "way overly bloated" version of a singleton. `private readonly static ThreadSafeSingleton instance = new ThreadSafeSingleton();` will suffice – Yuval Itzchakov Mar 29 '15 at 14:36

2 Answers2

3

The CLR executes static constructors only once. It is specified to do so. Therefore, instance is being initialized exactly once. That makes this thread-safe.

How the thread-safety is achieved is an implementation detail.

usr
  • 168,620
  • 35
  • 240
  • 369
0

Please find below implementation for thread safe singleton implementation.

Also, you can use this question useful. It provides double locking thread safety which doesn't hurt performance.

Find reference for static here

Find the reference here

The below code is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Not thread safe singleton

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton()
    {
    }

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

Thread safe implementation:

public sealed class Singleton { private static Singleton instance = null; private static readonly object padlock = new object();

Singleton()
{
}

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

}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Community
  • 1
  • 1
Akanksha Gaur
  • 2,636
  • 3
  • 26
  • 50