Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Lazy<T> a good solution for a thread safe lazy loaded singleton?

Tags:

We implemented a lazy loaded singleton using double locking on get to make sure the instance is only initialized once (and not twice due to thread race conditions).

I was wondering if simply using Lazy<T> is a good solution for this problem?

I.E.

private static Lazy<MyClass> _instance = new Lazy<MyClass>(() => return new MyClass());  public static MyClass Instance {     get     {         return _instance.Value;     } } 
like image 634
Ron Avatar asked May 06 '15 12:05

Ron


People also ask

Is Lazy T thread-safe?

By default, Lazy<T> objects are thread-safe. That is, if the constructor does not specify the kind of thread safety, the Lazy<T> objects it creates are thread-safe.

Are singletons thread-safe?

Is singleton thread safe? A singleton class itself is not thread safe. Multiple threads can access the singleton same time and create multiple objects, violating the singleton concept. The singleton may also return a reference to a partially initialized object.

Is lazy initialization good practice?

From MSDN: IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the object after creation. You must lock the object before accessing it, unless the type is thread safe.

What is Lazy T?

The Lazy<T> object ensures that all threads use the same instance of the lazily initialized object and discards the instances that are not used.


1 Answers

I suggest you to read referencede articles from comments:

  • Lazy Class
  • Implementing the Singleton Pattern in C#

In all cases the Lazy<T> class is thread-safe, but you need to remember that the Value of this type can be thread-unsafe, and can be corrupted in multithreading environment:

private static Lazy<MyClass> _instance = new Lazy<MyClass>(() => return new MyClass());  public static MyClass Instance {    get {       return _instance.Value;    } }  public void MyConsumerMethod() {     lock (Instance)     {         // this is safe usage         Instance.SomeMethod();     }      // this can be unsafe operation     Instance.SomeMethod(); } 

Also you can use any constructor you like depending on the environment of your application.

like image 178
VMAtm Avatar answered Oct 28 '22 07:10

VMAtm