A better way to do Singletons

In a recent class I was taking, Jeffery Richter was teaching another class next door.  My instructor was commenting on how good Jeffery’s Threading class was.  And one of the things he shared from that class was about Singleton initialization.   Most of the time when you see singletons you see them build as follows:

public class Singleton1

{

   private Singleton1 instance;

   private Object lockObject = new object();

   private Singleton1() { }

 

   public Singleton1 Instance

   {

      get

      {

         if (instance == null)

         {

            lock (lockObject)

            {

               if (instance == null)

               {

                  instance = new Singleton1();

               }

            }

         }

         return instance;

      }

   }

}

 

Sometimes you get a bit more advanced version of the same thing:

public class Singleton2

{

   private Singleton2 instance;

   private Mutex mut = new Mutex();

   private Singleton2() {}

 

   public Singleton2 Instance

   {

      get

      {

         if (instance == null)

         {

            mut.WaitOne();

            if (instance == null)

            {

               instance = new Singleton2();

               mut.ReleaseMutex();

            }

         }

         return instance;

      }

   }

}

 

There is also another way that we often see, and Jeffery feels is a much better and safer approach:

public class Singleton3

{

   private Singleton3 instance = new Singleton3();

   private Singleton3() { }

 

   public Singleton3 Instance

   {

      get

      {

         return instance;

      }

   }

}

He feels that the first two techniques could possibly fail or cause contention.  However, the third technique is guaranteed by how the framework loads the class definition.  I prefer this method and it is also less code.

 

Happy Coding!

Advertisements

About JohnMarkHowell

I am a professional software developer with over 20 years of experience. I currently specialize in Microsoft technologies such as VS, TFS, C#, VB.Net, WCF, WPF, WW, etc.
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s