ChallengeWhy is this wrong?
time to read 1 min | 40 words
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.
More posts in "Challenge" series:
- (01 Jul 2024) Efficient snapshotable state
- (13 Oct 2023) Fastest node selection metastable error state–answer
- (12 Oct 2023) Fastest node selection metastable error state
- (19 Sep 2023) Spot the bug
- (04 Jan 2023) what does this code print?
- (14 Dec 2022) What does this code print?
- (01 Jul 2022) Find the stack smash bug… – answer
- (30 Jun 2022) Find the stack smash bug…
- (03 Jun 2022) Spot the data corruption
- (06 May 2022) Spot the optimization–solution
- (05 May 2022) Spot the optimization
- (06 Apr 2022) Why is this code broken?
- (16 Dec 2021) Find the slow down–answer
- (15 Dec 2021) Find the slow down
- (03 Nov 2021) The code review bug that gives me nightmares–The fix
- (02 Nov 2021) The code review bug that gives me nightmares–the issue
- (01 Nov 2021) The code review bug that gives me nightmares
- (16 Jun 2021) Detecting livelihood in a distributed cluster
- (21 Apr 2020) Generate matching shard id–answer
- (20 Apr 2020) Generate matching shard id
- (02 Jan 2020) Spot the bug in the stream
- (28 Sep 2018) The loop that leaks–Answer
- (27 Sep 2018) The loop that leaks
- (03 Apr 2018) The invisible concurrency bug–Answer
- (02 Apr 2018) The invisible concurrency bug
- (31 Jan 2018) Find the bug in the fix–answer
- (30 Jan 2018) Find the bug in the fix
- (19 Jan 2017) What does this code do?
- (26 Jul 2016) The race condition in the TCP stack, answer
- (25 Jul 2016) The race condition in the TCP stack
- (28 Apr 2015) What is the meaning of this change?
- (26 Sep 2013) Spot the bug
- (27 May 2013) The problem of locking down tasks…
- (17 Oct 2011) Minimum number of round trips
- (23 Aug 2011) Recent Comments with Future Posts
- (02 Aug 2011) Modifying execution approaches
- (29 Apr 2011) Stop the leaks
- (23 Dec 2010) This code should never hit production
- (17 Dec 2010) Your own ThreadLocal
- (03 Dec 2010) Querying relative information with RavenDB
- (29 Jun 2010) Find the bug
- (23 Jun 2010) Dynamically dynamic
- (28 Apr 2010) What killed the application?
- (19 Mar 2010) What does this code do?
- (04 Mar 2010) Robust enumeration over external code
- (16 Feb 2010) Premature optimization, and all of that…
- (12 Feb 2010) Efficient querying
- (10 Feb 2010) Find the resource leak
- (21 Oct 2009) Can you spot the bug?
- (18 Oct 2009) Why is this wrong?
- (17 Oct 2009) Write the check in comment
- (15 Sep 2009) NH Prof Exporting Reports
- (02 Sep 2009) The lazy loaded inheritance many to one association OR/M conundrum
- (01 Sep 2009) Why isn’t select broken?
- (06 Aug 2009) Find the bug fixes
- (26 May 2009) Find the bug
- (14 May 2009) multi threaded test failure
- (11 May 2009) The regex that doesn’t match
- (24 Mar 2009) probability based selection
- (13 Mar 2009) C# Rewriting
- (18 Feb 2009) write a self extracting program
- (04 Sep 2008) Don't stop with the first DSL abstraction
- (02 Aug 2008) What is the problem?
- (28 Jul 2008) What does this code do?
- (26 Jul 2008) Find the bug fix
- (05 Jul 2008) Find the deadlock
- (03 Jul 2008) Find the bug
- (02 Jul 2008) What is wrong with this code
- (05 Jun 2008) why did the tests fail?
- (27 May 2008) Striving for better syntax
- (13 Apr 2008) calling generics without the generic type
- (12 Apr 2008) The directory tree
- (24 Mar 2008) Find the version
- (21 Jan 2008) Strongly typing weakly typed code
- (28 Jun 2007) Windsor Null Object Dependency Facility
Comments
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.
No return type?
... or should I say, no variable type.
Thilak,
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.
Darn!
The initializer will run only once during appdomain initialization, not on every thread.
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):
<t(string key, Func <t getter) {
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
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!
I think qbik has nailed it.
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.
If CreateSingleInstance will fail mySingleton will be NULL which I doubt is the expected value of it.
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.
It'll get initialized only on the 1st thread so you'll get NullReferenceException on subsequent threads.
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 :)
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.
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 :)
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:
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
{
}
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
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 :)
ThreadStatic does not get along well when operating in a web environment because IIS may not necessarily start and end your request on the same thread:
www.hanselman.com/.../...pContextCurrentItems.aspx
Comment preview