NetInverse Developers Blog

March 9, 2009
Category: .Net, Design Pattern — Tags: , — admin @ 8:18 pm

A typicaly Singleton implementation in C# looks like below:

    using System;

    public sealed class Singleton
    {
       private static volatile Singleton instance;
       private static object syncRoot = new Object();

       private Singleton() {}

       public static Singleton Instance
       {
          get
          {
             if (instance == null)
             {
                lock (syncRoot)
                {
                   if (instance == null)
                      instance = new Singleton();
                }
             }

             return instance;
          }
       }
    }

[MSDN]This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks. This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed.

Above solution looks perfect, however, actually the ‘Double-Checked Locking’ can be still broken under certain multi-processor machine. A recommended way to implement Singleton correctly is below:

    public sealed class Singleton
    {
        Singleton(){}
        public static Singleton Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        static class Nested
        {
            internal static readonly Singleton instance = new Singleton();
        }
    }

Above code looks weird, but correct. It leverages .Net’s Class Loader to achieve thread-safe.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

©2009 NetInverse. All rights reserved. Powered by WordPress