Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between these two Singleton implementations

I am learning how to implement some basic design patterns. Whilst learning the Singleton pattern I have noticed that there are two common implementations on the web:

// Possibly from: http://www.yoda.arachsys.com/csharp/singleton.html
// I cannot remember exact source, sorry :(

public sealed class Singleton
{
    // Static members are 'eagerly initialized', that is,
    // immediately when class is loaded for the first time.
    // .NET guarantees thread safety for static initialization
    private static readonly Singleton instance = new Singleton();

    // Private constructor prevents instantiation from other classes
    private Singleton() { }

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    public static Singleton() { }

    // Get the instance of the singleton
    public static Singleton getInstance()
    {
            return instance;
    }

}

and:

public class Singleton
{
  // Static, VOLATILE variable to store single instance
  private static volatile Singleton m_instance;

  // Static synchronization root object, for locking
  private static object m_syncRoot = new object();

  // Property to retrieve the only instance of the Singleton
  public static Singleton Instance
   {
      get
      {
          // Check that the instance is null
          if (m_instance == null)
          {
              // Lock the object
              lock (m_syncRoot)
              {
                  // Check to make sure its null
                  if (m_instance == null)
                  {
                      m_instance = new Singleton();
                  }
              }
          }

          // Return the non-null instance of Singleton
          return m_instance;
      }
  }
} 
  1. In what scenario would you opt to have eagerly initialized vs lazy initialized?
  2. Is the comment in the first example correct in saying that the initialization is thread safe? (I know it says it is, but it's the internet...)
like image 997
Stuart Blackler Avatar asked Sep 22 '26 03:09

Stuart Blackler


1 Answers

I definitely would go with your first implementation...

the second seems questionable to me... if you need/want a lazy implementation you could use Lazy<T> for that - since it is part of the framework it feels much more comfortable..

BTW: There are even more ways to implement the Singleton pattern... here is an excellent article.

like image 163
Yahia Avatar answered Sep 23 '26 15:09

Yahia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!