vendredi 15 mai 2015

How does a singleton property with a lock ensure thread safety?

I rarely use singletons, in this case it's appropriate. While trying to investigate the best implementation thereof I came across this bit of code which has left me believing I improperly understand how brackets encapsulate a "scope."

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;
            }
        }
    }
} 

I'm confused what happens when I attempt to access "Instance." Say I'm working on a logging singleton (my useful application for a singleton) and it has a method "WriteLine(string line)"

When I call:

Singleton.Instance.WriteLine("Hello!");

It maintains the lock during the execution of the entire method of "WriteLine?"

What if I assign the instance to an external variable like:

Singleton Console = Singleton.Instance;

Now there's a constant reference to the singleton outside of the singleton. Is Console.WriteLine("Hello!") also completely thread safe like Singleton.Instance.WriteLine("Hello!")?

Anyway, I'm just confused how this makes the singleton thread safe and whether or not it's only thread safe when the property is explicitly accessed. I thought Singlton.Instance.WriteLine("...") would pull out the Instance first, thereby leaving the scope of the lock, and then execute WriteLine on the returned instance, therefore performing the write after the lock has been released.

Any help on clearing up my misunderstanding of how this functions would be appreciated.

Aucun commentaire:

Enregistrer un commentaire