mostlylucid

STATIC ARCHIVE of mostlylucid.co.uk of old
posts - 916, comments - 758, trackbacks - 11

My Links

News

Archives

Post Categories

Misc. Coding

Why do so many people mess up Singletons?

I've written about this a few times now (use the search thingy to find where) but I'm still surprised how many people mess up the Singleton pattern.

 

For instance take:

if (blogSettingsSingleton == null)
                {
                    blogSettingsSingleton = new BlogSettings();
                }
                return blogSettingsSingleton;

 

Looks ok, right? But this is a classic poor pattern when dealing with multi-threaded apps. Why? Look at the initial 'if' statement, and think what happens if multiple treads hit this at the same time...one thread could be in the process of creating this object whilst the others are evaluating the condition...

If you're using Singletons PLEASE read this article. The singleton pattern article from Wikipedia has the following excellent implementation of a singleton:

/// <summary>
/// Class implements singleton pattern.
/// </summary>
public class Singleton
{
        // Private constructor to avoid other instantiation
        // This must be present otherwise the compiler provide 
        // a default public constructor
        private Singleton()
        {
        }
 
        /// <summary>
        /// Return an instance of <see cref="Singleton"/>
        /// </summary>
        public static Singleton Instance
        {
            get
            {
                /// An instance of Singleton wont be created until the very first 
                /// call to the sealed class. This a CLR optimization that ensure that
                /// we have properly lazy-loading singleton. 
                return SingletonCreator.CreatorInstance;
            }
        }
 
        /// <summary>
        /// Sealed class to avoid any heritage from this helper class
        /// </summary>
        private sealed class SingletonCreator
        {
          // Retrieve a single instance of a Singleton
          private static readonly Singleton _instance = new Singleton();
 
          /// <summary>
          /// Return an instance of the class <see cref="Singleton"/>
          /// </summary>
          public static Singleton CreatorInstance
          {
            get { return _instance; }
          }
        }
}

This is a lazy-initializing, thread safe singleton...does sacrifice *some* performance (see the earlier article for details of this) but it is FAR safer than the original I showed...

Oh, and one last thing...are you REALLY sure you need a Singleton? One horrible pattern I've seen is code is using Singletons to access database connections...this is VERY RARELY required and sacrifices a lot of the benefits which modern databases offer for concurrent access.

 

UPDATE: Umm...realized that I don't explain what a 'Singleton' is...essentially it's a pattern which limits the access of an object to a single caller at a time. Common uses for Singletons could be accessing files on a file-system where you really want to make sure that only one thread has access at one time. Oh, and to make things even more complicated you'd more commonly want to use a ReaderWriterLock in this scenario to allow many readers or a single writer...only of course you wouldn't...told you it was complicated! Oh, and to further complicate matters in VS2008 and above you'd probably want ReaderWriterLockSlim!

Print | posted on Sunday, January 27, 2008 4:47 PM | Filed Under [ .NET Code Snippets Patterns Performance ]

Comments have been closed on this topic.

Powered by: