James Michael Hare

...hare-brained ideas from the realm of software development...
posts - 136 , comments - 1089 , trackbacks - 0

My Links

News

Welcome to my blog! I'm a Sr. Software Development Engineer in Seattle, WA. I've been doing C++/C#/Java development for over 18 years, but have definitely learned that there is always more to learn!

All thoughts and opinions expressed in my blog and my comments are my own and do not represent the thoughts of my employer.

Blogs I Read

MCC Logo MVP Logo

Follow BlkRabbitCoder on Twitter

Tag Cloud

Archives

Post Categories

C#: System.Lazy<T> and the Singleton Design Pattern

So we've all coded a Singleton at one time or another.  It's a really simple pattern and can be a slightly more elegant alternative to global variables.  Make no mistake, Singletons can be abused and are often over-used -- but occasionally you find a Singleton is the most elegant solution.

For those of you not familiar with a Singleton, the basic Design Pattern is that a Singleton class is one where there is only ever one instance of the class created.  This means that constructors must be private to avoid users creating their own instances, and a static property (or method in languages without properties) is defined that returns a single static instance.

   1: public class Singleton
   2: {
   3:     // the single instance is defined in a static field
   4:     private static readonly Singleton _instance = new Singleton();
   5:  
   6:     // constructor private so users can't instantiate on their own
   7:     private Singleton()
   8:     {
   9:     }
  10:  
  11:     // read-only property that returns the static field
  12:     public static Singleton Instance
  13:     {
  14:         get 
  15:         {
  16:             return _instance; 
  17:         }
  18:     }
  19: }

This is the most basic singleton, notice the key features:

  • Static readonly field that contains the one and only instance.
  • Constructor is private so it can only be called by the class itself.
  • Static property that returns the single instance.

Looks like it satisfies, right?  There's just one (potential) problem.  C# gives you no guarantee of when the static field _instance will be created.  This is because the C# standard simply states that classes (which are marked in the IL as BeforeFieldInit) can have their static fields initialized any time before the field is accessed.  This means that they may be initialized on first use, they may be initialized at some other time before, you can't be sure when.

So what if you want to guarantee your instance is truly lazy.  That is, that it is only created on first call to Instance?  Well, there's a few ways to do this.  First we'll show the old ways, and then talk about how .Net 4.0's new System.Lazy<T> type can help make the lazy-Singleton cleaner.

Obviously, we could take on the lazy construction ourselves, but being that our Singleton may be accessed by many different threads, we'd need to lock it down.

   1: public class LazySingleton1
   2: {
   3:     // lock for thread-safety laziness
   4:     private static readonly object _mutex = new object();
   5:  
   6:     // static field to hold single instance
   7:     private static volatile LazySingleton1 _instance = null;
   8:  
   9:     // property that does some locking and then creates on first call
  10:     public static LazySingleton1 Instance
  11:     {
  12:         get
  13:         {
  14:             if (_instance == null)
  15:             {
  16:                 lock (_mutex)
  17:                 {
  18:                     if (_instance == null)
  19:                     {
  20:                         _instance = new LazySingleton1();
  21:                     }
  22:                 }
  23:             }
  24:  
  25:             return _instance;
  26:         }
  27:     }
  28:  
  29:     private LazySingleton1()
  30:     {
  31:     }
  32: }

This is a standard double-check algorithm so that you don't lock if the instance has already been created.  However, because it's possible two threads can go through the first if at the same time the first time back in, you need to check again after the lock is acquired to avoid creating two instances.

Pretty straightforward, but ugly as all heck.  Well, you could also take advantage of the C# standard's BeforeFieldInit and define your class with a static constructor.  It need not have a body, just the presence of the static constructor will remove the BeforeFieldInit attribute on the class and guarantee that no fields are initialized until the first static field, property, or method is called.

 

   1: public class LazySingleton2
   2: {
   3:     // because of the static constructor, this won't get created until first use
   4:     private static readonly LazySingleton2 _instance = new LazySingleton2();
   5:  
   6:     // Returns the singleton instance using lazy-instantiation
   7:     public static LazySingleton2 Instance
   8:     {
   9:         get { return _instance; }
  10:     }
  11:  
  12:     // private to prevent direct instantiation
  13:     private LazySingleton2()
  14:     {
  15:     }
  16:  
  17:     // removes BeforeFieldInit on class so static fields not
  18:     // initialized before they are used
  19:     static LazySingleton2()
  20:     {
  21:     }
  22: }

Now, while this works perfectly, I hate it.  Why?  Because it's relying on a non-obvious trick of the IL to guarantee laziness.  Just looking at this code, you'd have no idea that it's doing what it's doing.  Worse yet, you may decide that the empty static constructor serves no purpose and delete it (which removes your lazy guarantee).  Worse-worse yet, they may alter the rules around BeforeFieldInit in the future which could change this.

So, what do I propose instead?  .Net 4.0 adds the System.Lazy type which guarantees thread-safe lazy-construction.  Using System.Lazy<T>, we get:

   1: public class LazySingleton3
   2: {
   3:     // static holder for instance, need to use lambda to construct since constructor private
   4:     private static readonly Lazy<LazySingleton3> _instance
   5:         = new Lazy<LazySingleton3>(() => new LazySingleton3());
   6:  
   7:     // private to prevent direct instantiation.
   8:     private LazySingleton3()
   9:     {
  10:     }
  11:  
  12:     // accessor for instance
  13:     public static LazySingleton3 Instance
  14:     {
  15:         get
  16:         {
  17:             return _instance.Value;
  18:         }
  19:     }
  20: }

Note, you need your lambda to call the private constructor as Lazy's default constructor can only call public constructors of the type passed in (which we can't have by definition of a Singleton).  But, because the lambda is defined inside our type, it has access to the private members so it's perfect.

Note how the Lazy<T> makes it obvious what you're doing (lazy construction), instead of relying on an IL generation side-effect.  This way, it's more maintainable.  Lazy<T> has many other uses as well, obviously, but I really love how elegant and readable it makes the lazy Singleton.

 

 Technorati Tags: , , , , , , ,

 

Print | posted on Wednesday, May 19, 2010 6:41 PM | Filed Under [ My Blog C# Software .NET Fundamentals ]

Feedback

Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Very good article --- Thanks...
5/22/2010 7:10 AM | Ashvin Rajani
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Your LazySingleton1-example seems to be missing the 'volatile' keyword on the _instance-line. See MSDN Pattern & Practices: http://msdn.microsoft.com/en-us/library/ff650316.aspx

The rest is very clear. Thanks for your blog!
6/1/2010 1:57 AM | Rogier
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

@Rogier - good catch! I'll add that.
6/1/2010 8:19 AM | James Michael Hare
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Thanks James, this really is an elegant solution compared to the traditional double-check locking.

Cheers,
Jason
7/1/2010 11:16 PM | Jason Wingfield
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Very nice article! Well done. Especially the part that explains the trick with the static constructor at LazySingleton2
7/29/2010 8:23 AM | Paris Polyzos
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Good article James, please explain why in your LazySingleton3 you don't use lambda constructor with LazyExecutionMode, look on this article http://sankarsan.wordpress.com/2009/10/04/laziness-in-c-4-0-lazyt/
I think that it in LazySingleton3 you also rely on runtime trick to guarantee laziness.
It'll be clear way

private static readonly Lazy<LazySingleton3> _instance
= new Lazy<LazySingleton3>(() => new LazySingleton3(), LazyExecutionMode.EnsureSingleThreadSafeExecution);

Thanks,
Slava
9/28/2010 3:47 AM | slava pocheptsov
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

@Slava:

Actually, that form of the constructor disappeared when .NET 4.0 was officially released. LazyExecutionMode no longer exists, the enum is now called LazyThreadSafetyMode, and the particular value you want is LazyThreadSafetyModel.ExecutionAndPublication.

But, that said, the form of the constructor that does not specify the enum (like I used) already uses LazyThreadSafetyModel.ExecutionAndPublication so it is thread safe, I think this was changed between betas and the release of 4.0 so it is no longer of concern.

Thus I think my example still stands.

See http://msdn.microsoft.com/en-us/library/dd642329.aspx for more info.
9/28/2010 10:43 AM | James Michael Hare
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Thank you for this. I had a singleton class that initialized on the constructor, and I couldn't mock it with Moles because it would call the constructor before Moles could do anything, and this was the solution!
10/26/2010 5:38 PM | Rick
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

This seems like a really great technique, but I am still experiencing initialization issues. I've implemented a test case, using C# 4.0, of course, and when I call Instance, it is consistently null.

When setting a breakpoint on _instance it is never called. Perhaps I am not understanding something, but the main point is guaranteed initialization of Instance, yes?
2/19/2011 7:46 PM | Learning Coder
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Can you post your code? It sounds like there is something syntactically off. I assume you're talking about LazySingleton3?
2/23/2011 8:47 AM | James Michael Hare
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

How so?
3/3/2011 9:22 AM | James Michael Hare
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

It's worth mentioning the volatile thing in the original post, given that a significant proportion of the singleton implementation I've seen in the wild are broken in some manner.

That being said, has anyone actually tested what the gain from double checked locking is in this instance? Uncontested locks should be cheap to acquire, I'd be inclined to make the whole darn method synchronised and be done with it.
4/7/2011 7:27 PM | CurtainDog
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

@CurtainDog:

The double checked locking is pretty much standard (before Lazy at least). In fact I ran a quick test of 1,000,000 iterations of each singleton, and the fully-synchronized singleton is 6 times slower than the double-checked locking version.

So yes, the double-checked locking does by you something. And that's with just one thread, with multiple threads should perform even better since the locking is completely removed after the first iteration is created.
4/7/2011 8:34 PM | James Michael Hare
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

For completeness, you should signal to others that the class LazySingleton3 should not be derived from, which would allow multiple instances to be constructed indirectly through the construction of derived class instances, by marking LazySingleton3 as 'sealed'. Search for 'sealed' in http://msdn.microsoft.com/en-us/library/ms998558.aspx.
5/16/2011 4:21 PM | Terry Bondy
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Actually it's unnecessary, the class has only a private constructor which means it can't be derived from.
5/16/2011 6:20 PM | James Michael Hare
Gravatar

# A Generic Singleton Class

Nice work! Standing on the shoulders of giants, I have taken your post to the next level by encapsulating the Lazy<T> singleton in a generic class. See my blog post here: http://www.fascinatedwithsoftware.com/blog/post/2011/07/13/A-Generic-Singleton-Class.aspx

7/14/2011 8:04 AM | Larry Spencer
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Interesting how Singleton works. I like how you explain all these things, thanks a lot for container transportation Turkey time.
9/30/2011 9:52 AM | andrew
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Very nice, I really love the lazy<> of .net 4, the code looks more elegant and understandable :)

Thanks!
11/30/2011 8:55 PM | nXqd
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Andrew: Without a doubt, that is one of the most bizarre comments I've ever seen made on an article (tech related or otherwise). The code provided does not deal with transporting containers, nor does the article imply that it is time for turkey (well, I suppose there is never a bad time for turkey, except for prior to a long meeting).

Can you please explain what on earth possessed you to post that? The curiosity is killing me.
12/14/2011 3:39 PM | CodeTurkey
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

>Can you please explain what on earth possessed you to post that? The curiosity is killing me.

It's just a SEO bot trying to up that company's pagerank via your blog.
4/2/2012 12:07 PM | Charles
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Good article, special thanks for the IL / BeforeFieldInit background information so that I know why I should use Lazy<T> and not the static ctor "hack".
4/22/2012 7:08 AM | Harald-René Flasch
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Hi there,

I have always been using the following construction for singleton lazy loading. Please let me know your thoughts about it...

public class ItemTable
{
// Nested static class for lazy loading/creation
private static class ItemTableCreator
{
// Static object of ItemTable type instantiated with static constructor
internal static readonly ItemTable UniqueInstance;

// Static constructor to instantiate ItemTable class
static ItemTableCreator()
{
UniqueInstance = new ItemTable();
}
}

// Private instance constructor
private ItemTable()
{
}

// Public static property to access the ItemTable object
public static ItemTable Instance
{
get { return ItemTableCreator.UniqueInstance; }
}
8/12/2012 3:01 PM | Andrew
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

@Andrew:

Main thing I don't like about a manual constructed singletons like that is that you are hard-coding the lazy logic. In addition, having an explicit static constructor can be a slight performance hit (though may be a wash with using Lazy).
8/17/2012 3:56 PM | James Michael Hare
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Great example, thanks.

Now I have only one problem when using the lazy way, how to check if the class was initiated? I mean like this

private static readonly Lazy<FileLogManager> lazyFileLogManager = new Lazy<FileLogManager>
(() => new FileLogManager(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);

private FileLogManager() { }

public static FileLogManager Instance
{
get
{
if (??????? == null)
{
// I need to do some tasks here when the class first initiated
}
return lazyFileLogManager.Value;
}
}


9/26/2012 5:51 PM | JM
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

@JM:

You can use the property IsValueCreated in the Lazy<T> class to see if it has created it yet. Though be careful! In the logic you have sketched it would be possible for two threads to hit it at the same time, both do the init logic, then one creates the instance:

if (!lazyFileLogManager.IsValueCreated) ...

HOWEVER, you can add a call to do that stuff in the lambda you pass to your Lazy<T> constructor, and then with full thread safety mode only one will execute it:

private static readonly Lazy<FileLogManager> lazyFileLogManager = new Lazy<FileLogManager>(() => { DoSomeInitialization(); return new FileLogManager(); }, true);
9/26/2012 6:00 PM | James Michael Hare
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

It worked, thanks for your help.
10/1/2012 11:57 AM | JM
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Thank you for this article, it was useful in writtign my own post about singleton pattern in C#.
http://szulak.com/singleton-pattern-in-csharp/
11/20/2012 5:53 AM | szulak
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Nice article!!
1/30/2013 10:02 PM | SHaiju Janardhanan
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Nice article. Here's a generic that you can use. You can sort of think of it as a wrapper of Lazy<T>.

using System;

public abstract class Singleton<T> where T:new()
{
private static readonly Lazy<T> _instance = new Lazy<T>(() => new T());

protected Singleton()
{
}

public static T Instance
{
get
{
return _instance.Value;
}
}

}
2/28/2013 12:25 PM | Richard Collette
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

@Richard: Nice, only suggestion I have is instead of marking Singleton<T> as abstract, you mark it static and remove the protected constructor. The preferred way to make a static class in C# is to use the static class modifier, this makes the class sealed and disallows instantiation.
2/28/2013 12:31 PM | James Michael Hare
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

If I want to create a lazy singleton of a class which accepts constructor arguments, is the following a correct way to do it

public class LazySingletonWithArgs
{
private static Lazy<Storage> _instance;

private LazySingletonWithArgs()
{
}

public static Storage Instance(Config config)
{
if (!_instance.IsValueCreated)
{
string key = config.GetKey();
_instance = new Lazy<Storage>(() => new Storage(key), LazyThreadSafetyMode.ExecutionAndPublication);
}
return _instance.Value;
}
}
4/18/2013 11:12 PM | Mangal
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

One tip: Instead of creating a private constructor to prevent direct instantiation, you can make the class static.
2/26/2014 8:47 PM | Tony
Gravatar

# re: C#: System.Lazy<T> and the Singleton Design Pattern

Nice Post :)
but what if _instance.Value throws an error...
as _instance.Value will call private constructor of LazySingleton3 and suppose it throws an unhandled exception(for ex: code in constructor was hitting a database which was down).

Now whenever i call _instance.Value it will rethrow same exception again and again until application domain is recycled(as exception will be cached).

So can you please advice on how to tackle this situation.

Thanks
7/10/2014 9:10 AM | Abhijit Shetty
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 
 

Powered by: