.NET Tip: Creating a Thread-Safe Singleton

A singleton is used to ensure that there is only one instance of a class created. A singleton also provides the single point of access to that one instance of the class. Singletons can be used for a wide range of reasons, from a better means of managing global variables to creating abstract factories to maintaining a state machine for you application. Regarless of your use of the singleton, I will show you how to create a bare-bones singleton that can be created in a thread-safe manner. Here is the code:

public sealed class Singleton
{
   private static Singleton _Instance = null;
   private static readonly object _Lock = new object();

   private Singleton()
   {
   }

   public static Singleton Instance
   {
      get
      {
         lock (_Lock)
         {
            if (_Instance == null)
               _Instance = new Singleton();

            return _Instance;
         }
      }
   }
}

First, the class is marked as sealed so that another class can't derive from it and change its behavior. This simple version of a singleton has only two private variables. One is used to store the actual instance of the Singleton class and the other is used as a lock to ensure that multiple threads cannot create new instances of the singleton at the same time. The contrstructor is declared as private so that there is no way to create a Singleton other than using the Instance method. The Instance method uses the _Lock variable to make sure no other threads are retrieving the instance of the singleton at the same time. If the lock is successful, a new instance of Singleton is created if it does not already exist, and then that instance is returned. To extend the Singleton class, you simply need to add properties and methods that would be appropriate for your application. Using the private constructor and Instance method will guarantee that only one copy of your class is ever active in your application.

The Singleton pattern is one of the orginal "Gang of Four" design patterns. I would highly recommend you read Design Patterns by Gamma, Helm, Johnson, and Vlissides to learn more about patters.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.



Comments

  • Simpler

    Posted by richard_deeming on 02/08/2008 01:19pm

    Just use a field initializer - the instance will not be created until the class is first accessed, and the initializer is guaranteed to be thread-safe.
    
    public sealed class Singleton
    {
        private static readonly Singleton _Instance = new Singleton();
        
        private Singleton()
        {
        }
        
        public static Singleton Instance
        {
            get { return _Instance; }
        }
    }

    Reply
  • Just a remark

    Posted by SoftwareTester on 02/03/2008 10:28am

    I've seen a document about threadsafe singleton before http://www.yoda.arachsys.com/csharp/singleton.html I think this one explains more differences and WHY and WHEN to use WHAT way to do it

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds