Ayende @ Rahien

My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:


+972 52-548-6969

, @ Q c

Posts: 6,128 | Comments: 45,550

filter by tags archive

ChallengeWhy is this wrong?

time to read 1 min | 40 words

Can you figure out why this is a horribly wrong thing to do?

private static readonly MySingleton mySingleton = CreateSingleInstance();
A free license of Rhino Mocks will be raffled between the people who will correctly answer it.

More posts in "Challenge" series:

  1. (28 Apr 2015) What is the meaning of this change?
  2. (26 Sep 2013) Spot the bug
  3. (27 May 2013) The problem of locking down tasks…
  4. (17 Oct 2011) Minimum number of round trips
  5. (23 Aug 2011) Recent Comments with Future Posts
  6. (02 Aug 2011) Modifying execution approaches
  7. (29 Apr 2011) Stop the leaks
  8. (23 Dec 2010) This code should never hit production
  9. (17 Dec 2010) Your own ThreadLocal
  10. (03 Dec 2010) Querying relative information with RavenDB
  11. (29 Jun 2010) Find the bug
  12. (23 Jun 2010) Dynamically dynamic
  13. (28 Apr 2010) What killed the application?
  14. (19 Mar 2010) What does this code do?
  15. (04 Mar 2010) Robust enumeration over external code
  16. (16 Feb 2010) Premature optimization, and all of that…
  17. (12 Feb 2010) Efficient querying
  18. (10 Feb 2010) Find the resource leak
  19. (21 Oct 2009) Can you spot the bug?
  20. (18 Oct 2009) Why is this wrong?
  21. (17 Oct 2009) Write the check in comment
  22. (15 Sep 2009) NH Prof Exporting Reports
  23. (02 Sep 2009) The lazy loaded inheritance many to one association OR/M conundrum
  24. (01 Sep 2009) Why isn’t select broken?
  25. (06 Aug 2009) Find the bug fixes
  26. (26 May 2009) Find the bug
  27. (14 May 2009) multi threaded test failure
  28. (11 May 2009) The regex that doesn’t match
  29. (24 Mar 2009) probability based selection
  30. (13 Mar 2009) C# Rewriting
  31. (18 Feb 2009) write a self extracting program
  32. (04 Sep 2008) Don't stop with the first DSL abstraction
  33. (02 Aug 2008) What is the problem?
  34. (28 Jul 2008) What does this code do?
  35. (26 Jul 2008) Find the bug fix
  36. (05 Jul 2008) Find the deadlock
  37. (03 Jul 2008) Find the bug
  38. (02 Jul 2008) What is wrong with this code
  39. (05 Jun 2008) why did the tests fail?
  40. (27 May 2008) Striving for better syntax
  41. (13 Apr 2008) calling generics without the generic type
  42. (12 Apr 2008) The directory tree
  43. (24 Mar 2008) Find the version
  44. (21 Jan 2008) Strongly typing weakly typed code
  45. (28 Jun 2007) Windsor Null Object Dependency Facility



hmm, maybe this is the reason:

"Note: Do not specify initial values for fields marked with ThreadStaticAttribute, because such initialization occurs only once, when the class constructor executes, and therefore affects only one thread. If you do not specify an initial value, you can rely on the field being initialized to its default value if it is a value type, or to a null reference (Nothing in Visual Basic) if it is a reference type." (MSDN)

So you would have correct instance for the first thread that access the singleton, and null's for all other threads. And the readonly flag stops you from initializing the field in any other place.

Thilak Nathen

... or should I say, no variable type.

Ayende Rahien


That is actually a bug in my post about a bug :-)

Fixed, thanks for spotting this.


Initialization of ThreadStatic variables only happen once. So on other threads the value will be the default value, being null for reference types.


The initializer will run only once during appdomain initialization, not on every thread.

Bill Barry

While I dislike the usage of the tread static attribute in general, This case in particular you seem to be suggesting you want a singleton but here you will not have a singleton.

In place of the thread static attribute, I like to use the following pattern (which I also use for accessing cache and session):

public class Memoize {

    public static T Execute

<t(string key, Func <t getter) {

        var obj = (T)CallContext.GetData(key);

        if (!Equals(obj, default(T))) {

            return obj;


        obj = getter();

        CallContext.SetData(key, obj);

        return obj;



Because different threads will have different instances of the field, so it's not a Singleton anymore, AND only one of the threads will be properly initialized with a MySingleton type, the others will be null.

PD: A free Rhino Mocks license? Is it the "Ultimate" version or what? :D

John Simons

Because the ThreadPool reuses threads.

Specially bad in web scenarios, because the web pipeline uses the ThreadPool to handle requests.


Bad because

0) Little known - in a asp.net web call, the actual thread used can actually change during the asp.net event processing. use context instead.

1) initialization only on the first thread

2) any threadpool threads will possibly be reused and hence the "thread-specific singleton" will behave oddly.

3) It's magic!

Nick Berardi

I think qbik has nailed it.

Mohamed Meligy

You'd use ThreadStatic so that you have only one MySingleton in every thread (by default MySingleton should be only one instance for all threads, using ThreadStatic you have N MySingleton for N threads).

The problem is that the assignment to a static field (to "CreateSingleInstance()" return value) is just the same as if it was written inside a static constructor, and a static constructor is called only once, so, the second thread and beyond will not call it, meaning will NOT assign MySingleton a value, and it will remain to default(MySingleton), null.

Dmitriy Nagirnyak

If CreateSingleInstance will fail mySingleton will be NULL which I doubt is the expected value of it.

Diego Mijelshon

Well, qbik basically nailed it, so there's not a lot to say.

I might add that calling "singleton" something that will (should) actually have one instance per thread is a semantic mistake.

Rule of thumb is, never make a ThreadStatic readonly and never initialize inline. Instead, use an accessor that checks for null.

Krzysztof Kozmic

It'll get initialized only on the 1st thread so you'll get NullReferenceException on subsequent threads.

Mikael Svenson

qbik got it spot on. I made this mistake myself in early .net days. It pays to think and read the manual every now and then :)

Stijn Guillemyn

First off, I think a singleton should always be one single instance, not an instance per thread. If you want a single instance per thread, you shouldn't call it a singleton, but threadInstance of something like that.

Secondly, this code will cause pain. Certainly if you're not executing on the first thread, as stated above, the only thread were the variable would be initialized.

Thinking of it, would this thread always be the UI thread? Or is this conclusion a bridge too far? If true, code that depends on your 'singleton' instance would then have UI thread affinity? So a null reference check could be used as a check if you're on the UI thread? :)

Or am I wrong about this?


ThreadStaticAttribute indicates that the value of a static field is unique for each thread.

Luis Abreu

I think that code will only run initialization once (for the 1st thread that access the value). The correct approach would be to wrap the field in a property which checks for null before returning a reference to that field.


I guess because we don't know how CreateSingleInstance is implemented :)

Alun Harford

This will return null for all threads that didn't call the static initializer (ie. all but one). That's probably not what you wanted.


Does this code even compile?

By using the Readonly attribute you are saying MySingleton will only be assigned within the field initializer, once that's done it won't be assigned again.

Since this field is marked as thread static the field initilizer will only run once when the object is first created. So if you try and access the field from other threads you'd get a null reference exception.

Worse yet because its readonly you'd be unable to assign a new value to it.

Take the following code:


    static void Main(string[] args)



        Thread t = new Thread(new ThreadStart(run));





    static void run()


        if (Factory.mySingleton == null)


            Console.WriteLine("SingleTon is null");               




            Console.WriteLine("Singleton is not null");



If you run this you will find it's null when called from a new thread. Now if you try and assign it a value in the run method when it's null, the code will no longer compile because of the read only attribute.

So you end up with a null field you can only access from a single thread, which would be the thread the static field initalizer ran on.


Just realized I left off my Factory although you should be able to figure I meant it to be:

public class Factory



    public static readonly object mySingleton = new object();




"Do not specify initial values for fields marked with because such initialization occurs only once, when the class constructor executes, and therefore affects only one thread. If you do not specify an initial value, you can rely on the field being initialized to its default value if it is a value type, or to null if it is a reference typ".

"Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed."

Personally I think that the semantic fault is the worst, it can't be a singleton if it would (potentially) be initialized one time for each thread accessing it!

Greetings from sweden /jocke

Tobin Harris

In many cases it's more flexible to use a container for specifying lifecycle, rather than hard coding the desired one-instance-per-thread singleton behaviour. That could allow the component to be adapted and tested in different contexts (web, for example).

Other than that, the "subsequent threads will have nulls" problem raised by @qbik is obvioiusly a serious issue :)

Comment preview

Comments have been closed on this topic.


  1. The worker pattern - 18 hours from now

There are posts all the way to May 30, 2016


  1. The design of RavenDB 4.0 (14):
    26 May 2016 - The client side
  2. RavenDB 3.5 whirl wind tour (14):
    25 May 2016 - Got anything to declare, ya smuggler?
  3. Tasks for the new comer (2):
    15 Apr 2016 - Quartz.NET with RavenDB
  4. Code through the looking glass (5):
    18 Mar 2016 - And a linear search to rule them
  5. Find the bug (8):
    29 Feb 2016 - When you can't rely on your own identity
View all series


Main feed Feed Stats
Comments feed   Comments Feed Stats