A Simple Threadsafe Singleton

Tags: Design Patterns

The most famous design pattern and most reviled is the singleton.  Its what you can use if you want only one instance of a class.  Its disliked because it violates separation of concerns and makes your class more difficult to test.  Its still found in a lot of codebases I've seen so its worth knowing how to implement it correctly.

Common Singleton

A common way of implementing a singleton is to have the instance creation inside a public "Instance" property.  In the getter, you check if the instance exists, if it doesn't create it.  Then you make the constructor private and there you go, only one instance.

		private static Singleton theInstance;

		private Singleton() { }

		public static Singleton TheInstance
		{
			get
			{
				if (theInstance == null)
					theInstance = new Singleton();
				return theInstance;
			}
		}

Problem with this appraoch is its not threadsafe.  So then you gotta add locking.  This makes things more complicated and even with the proper locking, still has the possibility of weird memory allocation timing problems.

A Simpler and Threadsafe Way

Here's a nifty singleton that Jon Skeet recommends.

		// static initializer is threadsafe
		private static readonly Singleton instance = new Singleton();

		private Singleton() { }

		public static Singleton Instance { get { return instance; } }

Ins't that nice looking?  All you gotta do is make a static readonly variable to hold the instance and inialize the Singleton there.  The static initializer is guaranteed to be threadsafe.

Not So Lazy

In most casses the constructor won't be called until you access the instance property, but this is not guaranteed.  It might just go ahead and create the instance on app start.  There's a little trick to get around that though.

More Lazy

If you add a static constructor it will only initialize it right befrore the class is used.  

static Singleton() { }

There's a rule in C# that enforces this, I don't know the intracacies of it.  This singleton implemetation should be sufficient for 99% of cases.  In most cases I would imagine laziness is not really that big a deal unless you have some heavy duty singleton with lots of overhead going on, not too likely.

More

More about singletons from Mr. Skeet

No Comments

Add a Comment