samedi 22 juin 2019

What are the dangers of non thread safe singleton?

Recently I found this article that explains how to implement a thread safe singleton pattern in C#. However I wonder how important it is to make your singleton thread safe what and what are the dangers of having your singleton class non thread safe. Consider a very simple, non thread safe, implementation of a singleton pattern:

public class ThreadNotSafeSingleton
{
    public static ThreadNotSafeSingleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new ThreadNotSafeSingleton();
            }

            return _instance;
        }
    }

    private static ThreadNotSafeSingleton _instance;

    private ThreadNotSafeSingleton()
    {
    }
}

Now let's say, due to the fact that this code is non thread safe, two threads will enter this line of code _instance = new ThreadNotSafeSingleton();. In this case, the first thread will initialize _instance field and then the second one will initialize _instance field again, any way as a result you will have a single _instance existing in your application.

So what is the big deal here then? I know, if you have more complex code, and your constructor runs some other code that may not be thread safe it may be dangerous. But are there any problems with non thread safety if your singleton is that simple?

Aucun commentaire:

Enregistrer un commentaire