Murder, Blood and Thread Safe Singletons

Saturday, June 19, 2010 – 7:16 PM

It’s Saturday and I’ve been working on my book on Parallel Programming, except for a brief break to go to CrossFit.

Useful Piece of Information #1: Don’t do pull-ups until your hands are trashed if you’re planning on spending the afternoon typing.

I had lots of useful replies to my tweet asking how to get blood off a keyboard, both Cyber Clean and Hydrogen Peroxide with a Q-Tip seem popular. Makes me wonder exactly what those “other people” were going to need keyboard cleaning. And by association this brings me to…

Useful Piece of Information #2: The collective noun for Crows is…

“A murder of crows”

That was easy.

Useful Piece of Information #3: You can use the Lazy<T> class to implement a thread safe singleton.

public sealed class LazySingleton
    private static readonly Lazy<LazySingleton> _instance = 
        new Lazy<LazySingleton>(() => new LazySingleton() );
    private LazySingleton() { }
    public static LazySingleton Instance
        get { return _instance.Value; }

Reed Copsey Jr. blogged about this and he gave me some pointers on my initial implementation. Here I’ve sealed the class and made the constructor private, rather than protected. Usually I’m not a big fan of sealing classes but in

Jon Skeet’s post on singletons is also worth a read. There are several alternative implementations and Jon’s post describes many of the tradeoffs. I like this one because it’s not only simple but also very readable, whereas in my opinion some of the alternatives are not.

Anyway… Three useful pieces of information is you lot for the day and “Appendix A: Supporting Patterns” beckons.

  1. 4 Responses to “Murder, Blood and Thread Safe Singletons”

  2. Why use singletons at all? They are hell when writing unit tests. Singletons lets the developer hide vital dependencies.

    By redsolo on Jun 21, 2010

  3. Redsolo,

    Agreed. But if you need a singleton this is an interesting implementation. You’ll notice that knowing how to clean blood of keyboards and the collective noun for crows aren’t exactly things you really need either :).


    By Ade Miller on Jun 21, 2010

  1. 2 Trackback(s)

  2. Jun 20, 2010: Dew Drop – June 20, 2010 | Alvin Ashcraft's Morning Dew
  3. Jun 20, 2010: Tweets that mention Murder, Blood and Thread Safe Singletons | #2782 - Thinking about agile (small 'a') software development, patterns and practices for building Microsoft .NET applications. --

Sorry, comments for this entry are closed at this time.