Ayende @ Rahien

Refunds available at head office

Challenge: Why is this wrong?

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

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

Comments

qbik
10/18/2009 09:10 PM by
qbik

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
10/18/2009 09:26 PM by
Thilak Nathen

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

Ayende Rahien
10/18/2009 09:40 PM by
Ayende Rahien

Thilak,

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

Fixed, thanks for spotting this.

Frank
10/18/2009 09:42 PM by
Frank

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

Dmitry
10/18/2009 10:09 PM by
Dmitry

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

Bill Barry
10/18/2009 11:04 PM by
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;

    }

}
alberto
10/18/2009 11:29 PM by
alberto

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
10/19/2009 12:12 AM by
John Simons

Because the ThreadPool reuses threads.

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

Philip
10/19/2009 12:42 AM by
Philip

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
10/19/2009 12:53 AM by
Nick Berardi

I think qbik has nailed it.

Mohamed Meligy
10/19/2009 01:07 AM by
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
10/19/2009 02:00 AM by
Dmitriy Nagirnyak

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

Diego Mijelshon
10/19/2009 02:21 AM by
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
10/19/2009 05:59 AM by
Krzysztof Kozmic

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

Mikael Svenson
10/19/2009 06:27 AM by
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
10/19/2009 09:21 AM by
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?

Sergey
10/19/2009 01:09 PM by
Sergey

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

Luis Abreu
10/19/2009 01:41 PM by
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.

tihobrazov
10/19/2009 01:51 PM by
tihobrazov

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

Alun Harford
10/19/2009 04:12 PM by
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.

Josh
10/19/2009 07:18 PM by
Josh

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:

    [MTAThread]

    static void Main(string[] args)

    {


        run();


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

        t.Start();

        t.Join();

        Console.Read();


    }



    static void run()

    {


        if (Factory.mySingleton == null)

        {

            Console.WriteLine("SingleTon is null");               

        }

        else

        {

            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.

Josh
10/19/2009 07:20 PM by
Josh

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

public class Factory

{

    [ThreadStatic]

    public static readonly object mySingleton = new object();

}

jocke
10/19/2009 07:44 PM by
jocke

msdn.microsoft.com/en-us/library/system.threadstaticattribute.aspx

"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".

http://www.yoda.arachsys.com/csharp/singleton.html
"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
10/19/2009 11:31 PM by
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 :)

Comments have been closed on this topic.