A Lazier Singleton with .NET 4.0

This post examines how the new Lazy<T> type can improve standard implementations of the Singleton pattern in C#.

I will ignore for the moment the common jeremiads against the Singleton pattern and the reports made by some latter-day design pattern nihilists that the Singleton is dead.   I do not mean to imply that they are wrong – it’s just that it galls me that the Singleton pattern should be the object of such scorn and ridicule when the Flyweight is allowed to go along its merry way.

Besides which, the Singleton and the Facade are the only patterns I can write from memory and without a lot of research, so I love ‘em.

The best source for design patterns in C# is probably Judith Bishop’s C# 3.0 Design Patterns published by O’Reilly Press, which provides C# versions of all 23 patterns from the Gang of Four’s Elements of Reusable Object-Oriented Software.  The elegant implementation of the Singleton pattern she recommends looks like this:

 

public sealed class Singleton {
   // Private Constructor
   Singleton( ) { }

   // Private object instantiated with private constructor
   static readonly Singleton instance = new Singleton( );

   // Public static property to get the object
   public static Singleton Instance {
          get { return instance;}
       }
}

There is a problem with this, however.  Because of the way classes with static methods work in C# (or in this case, a static property), type instantiation of the private Singleton field instance happens at an unexpected point.  For an interesting if somewhat dense read on the effect of the beforeFieldInit flag, go here.

I will simply demonstrate the problem by adding some tracking code to Judith Bishop’s recommended implementation:

    public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton();
        private Singleton()
        {
            // no default constructor
            Console.WriteLine(" >> singleton initialized");
        }

        public static Singleton Instance
        {
            get
            {
                Console.WriteLine("before singleton retrieval");
                return instance;

            }
        }
    }

I will retrieve an instance of this Singleton class from a console application like so:

    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Calling Singleton instance");
            var s = Singleton.Instance;
            Console.WriteLine("Finished calling Singleton instance");
            Console.ReadLine();
        }
    }

When will the private type be initialized? When will the private constructor be called?  In w

hat order do you think the Console.WriteLines will be invoked?

Ideally the static members of this class would be initialized only when we needed them, and the output would be:

  1. Calling Singleton instance
  2. before singleton retrieval
  3. >> singleton initialized
  4. Finished calling Singleton instance

In actuality, however, this is the result:

singlton_results_1

This is not so bad, you may be thinking.  If our singleton is a large object this creates some additional strain to the system – but as long as the Singleton instance gets used fairly soon after it is instantiated it’s no big deal.

However, what if I come in after you have coded the singleton and decide to add another static method to your class — not understanding the intricate details of beforeFieldInit – like this:

        public static void Test()
        {
            Console.WriteLine("testing singleton");
        }

 

and rewrote the calling code like this:

            Console.WriteLine("Calling Singleton test method");
            Singleton.Test();
            Console.WriteLine("Calling Singleton instance");
            var s = Singleton.Instance;
            Console.WriteLine("Finished calling Singleton instance");
            Console.ReadLine();

 

It may not be immediately obvious but I have seriously messed up your code.  Here is the output:

singlton_results_2

Even if we never retrieve the Singleton instance, it will still be initialized when any other static method on our type is called – this is commonly known as a language runtime bummer.

.NET 4.0 introduces a new generic type called Lazy<T> which helps us out of this dilemma.  Lazy<T> is a wrapper class that facilitates thread safe, lazy instantiation of objects.  We can use it to create a new Singleton implementation that replaces the private static Singleton instance with a private static Lazy<Singleton>  instance.  The Instance property will also require a small rewrite to pull our Singleton out of the Lazy wrapper.

The full implementation of the lazy version of the singleton looks like this:

    public sealed class LazySingleton
    {
        // Private object with lazy instantiation
        private static readonly Lazy<LazySingleton> instance = 
            new Lazy<LazySingleton>(
                delegate { 
                    return new LazySingleton(); 
                }
                //thread safety first
                ,LazyExecutionMode.EnsureSingleThreadSafeExecution);

        private LazySingleton()
        {
           // no public default constructor
        }

        // static instance property
        public static LazySingleton Instance
        {
            get{ return instance.Value; }
        }
    }

Some things of note:

1. I pass a delegate as the first parameter to the Lazy constructor. There is a no parameter constructor for the generic Lazy<T> class, but it requires that type T have a public default constructor – which I obviously do not want to provide.  The delegate parameter allows me to indicate that I want to use a different constructor – in order to pass a constructor parameter to Type T, for instance, or to invoke a private constructor, in this case – than the default. 

2. The second parameter, also optional, tells the Lazy instance that I want the lazy instantiation of type T to be thread safe.

3. I retrieve the wrapped type T by asking for the Lazy type’s Value property.

Now it’s time for a contest. I add some Console.WriteLine statements as in the original and I append the malicious static Test() method as in the original.  I rewrite my Console app code to call my original Singleton code and then the new and improved — .NET 4.0 enhanced — Lazy Singleton code:

    Console.WriteLine("Calling Singleton test method");
    Singleton.Test();
    Console.WriteLine("Calling Singleton instance");
    var s = Singleton.Instance;
    Console.WriteLine("Finished calling Singleton instance");
    Console.WriteLine();

    Console.WriteLine("Calling Lazy Singleton test method");
    LazySingleton.Test();
    Console.WriteLine("Calling Lazy Singleton instance");
    var lazyS = LazySingleton.Instance;
    Console.WriteLine("Finished calling Lazy Singleton instance");
    Console.ReadLine();

and get the following, very pleasing, results:

singlton_results_3

Now that’s lazy!

One thought on “A Lazier Singleton with .NET 4.0

Comments are closed.