3

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...)
Stuart Blackler
  • 3,732
  • 5
  • 35
  • 60
  • possible duplicate of [What's a good threadsafe singleton generic template pattern in C#](http://stackoverflow.com/questions/100081/whats-a-good-threadsafe-singleton-generic-template-pattern-in-c-sharp) – H H Feb 04 '12 at 11:44
  • This has been discussed and blogged to death. You really have to focus it on something new or very specific. – H H Feb 04 '12 at 11:46
  • If you use .net 4 you can optionally use Lazy (http://msdn.microsoft.com/fr-fr/library/dd642331.aspx) – vc 74 Feb 04 '12 at 11:59
  • @HenkHolterman, I don't think so. That question is asking what is a good implementation, I'm asking about the thread safety and example usage :/ – Stuart Blackler Feb 04 '12 at 12:02
  • WRT 1..access modifier not allowed for static constructor. – Myles McDonnell Feb 04 '12 at 15:53
  • WRT 1..as CodeInChaos has pointed out, 1 is also lazy..the statement in the comments is incorrect (in .Net 4.0 at least, haven't checked others) 'instance' field is not initialised until it is accessed. Simply loading the class does not cause initialisation of static members. – Myles McDonnell Feb 04 '12 at 16:00

6 Answers6

3

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.

Yahia
  • 69,653
  • 9
  • 115
  • 144
  • Thanks for the link, it's interesting to see the implementation using `Lazy` :) – Stuart Blackler Feb 04 '12 at 12:04
  • 1
    you learn something everyday, I was thoroughly bored with all conversation about singletons, but I didn't know about Lazy. Now I'm looking forward to the next stupid interview question I get about singletons. Thx Yahia. – Myles McDonnell Feb 04 '12 at 15:46
2

I'm not sure but it looks like you got those examples from here: http://www.yoda.arachsys.com/csharp/singleton.html

If not, read through it. There are a couple of thoughts on the two versions. If you ask me personally: I would go for the 2nd solution if I needed to know if the singleton has already been initialized or not.

If you don't have to deal with multithreading, I would use an even simpler approach (see the "Bad Code" examples in the references link).

Krumelur
  • 32,180
  • 27
  • 124
  • 263
  • ". If you ask me personally: I would go for the 2nd solution if I needed to know if the singleton has already been initialized or not." Read your link. The second second example is listed as broken there. – CodesInChaos Feb 04 '12 at 11:51
  • Possible misunderstanding here: the 2nd version of the linked document = "Second version - simple thread-safety". But I agree, that was not clearly stated. – Krumelur Feb 04 '12 at 11:53
  • I've read a lot of stuff this morning regarding all sorts of design patterns as I am implementing them in all the languages I know, so it could have came from there. It's just the two I noted down. Thanks for the link again :) Bad code is bad for a reason? Why would you recommend using that? – Stuart Blackler Feb 04 '12 at 11:58
  • To my understanding, the "bad code" refers to the fact that it is not multihreading safe. If there is only one thread, there is need to make it more coplicated than required. In that sense I would recommend the simpler/simplest solution. – Krumelur Feb 04 '12 at 19:35
2

The first one is safe and lazy.

static constructors are guaranteed to be executed only once, and immediately before the first access to Instrance. If there is a static constructor(even if empty) then static field initializations are guaranteed to execute directly before the static constructor. If there is no static constructor, field initialization may occur earlier.


The second one is lazy, but I'm not sure if the double-lock pattern is valid like this. I suspect that it is broken, at least in the ECMA memory model.


Personally I'd avoid any Class.Instance singleton pattern in favour of IoC singletons in most situations.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
1

1) that's entirely a design choice. Init up front or init when required.

2) Yes, it is thread safe as the CLR guarantees single threaded object initialisation. (static and instance)

EDIT

personally, in the first example, I make the Instance field public and dispense with the getter. Be interested to know if there is any reason that this is a bad idea?

Myles McDonnell
  • 12,943
  • 17
  • 66
  • 116
1

It's a singleton so I'd go for option 1, unless it's a massive object that's not always even needed. But I probably would not make a singleton for something that's often not used at all.

MrFox
  • 4,852
  • 7
  • 45
  • 81
0

Both implementations are fine, so it depends on what you need.

If performance is not an issue, use the eagerly created instance of the first one. Otherwise, use the second one, in which only the first access is synchronized.

Tarek
  • 1