Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 509
ThisHandleNotInUse Avatar asked May 15 '15 12:05

ThisHandleNotInUse


People also ask

How do you ensure thread safety in singleton?

Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.

How a singleton implementation can be made thread-safe in C#?

Thread safe // mutex lock used forthread-safety. In the above code, a mutex lock is implemented for mutual-exclusion. Similarly, in the code below, a nested private class is implemented. This allows a single instance of Singleton when it is referenced for the first time in getObj() method.

Why singleton beans are not thread-safe?

If there is any global variable defined the singleton class then it will not be thread safe because if multiple thread share the singleton object and execute the method which can updates the global variable it will not be thread safe.

What is singleton lock?

Thread Safety Singleton In the code, the thread is locked on a shared object and checks whether an instance has been created or not. It takes care of the memory barrier issue and ensures that only one thread will create an instance.


1 Answers

Does Singleton.Instance.WriteLine("Hello!"); maintain the lock during the execution of the entire method of WriteLine?

No, the lock guards only the creation of your singleton. WriteLine executes unlocked (unless, of course, it obtains its own lock internally).

Is Console.WriteLine("Hello!") also completely thread safe like Singleton.Instance.WriteLine("Hello!")?

It is equally as safe or unsafe as Singleton.Instance, because the lock is not maintained outside of Instance's getter.

Anyway, I'm just confused how this makes the singleton thread safe

Lock makes the process of obtaining the instance of your singleton thread-safe. Making the methods of your singleton thread-safe is a process that does not depend on whether your object is a singleton or not. There is no simple turn-key one-fits-all solution for making a thread-unsafe object behave in a thread-safe way. You address it one method at a time.

like image 167
Sergey Kalinichenko Avatar answered Oct 06 '22 00:10

Sergey Kalinichenko