Reputation: 15314
I'm a .NET and Java developer who is relatively new to threading. I'd like to know why static fields, static constructors, etc are generally considered "threadsafe".
For example, when constructing a singleton in .NET, one of the tricks to make it threadsafe is to make some of the components of the pattern static.
Please let me know if any of my above assumptions are incorrect.
Upvotes: 2
Views: 5637
Reputation: 881423
Your above assumptions are incorrect. A static field is no more threadsafe than any other field.
Even in creating a singleton, the flag/pointer/item that indicates the object has already been built has to be protected by a synchronisation primitive if there's a possibility it may be called by multiple threads simultaneously.
The reason you use a static (class-level) variable for singletons is because you only want one object of the class. Using an object-level variable would restrict you to one object per object rather than one object per class, and one object per object is, well, just a regular object :-)
Upvotes: 3
Reputation: 51329
Static fields are not inherently thread safe- this is a fallacy. Static has nothing to do with threading really. It just means that the field is associated with a type, and not an instance of a type. The only thing to note about thread safety with regard to statics is that they are commonly set by a static constructor, and are commonly readonly e.g.:
class Foo {
// You can safely read `five` from any thread
public static readonly int five = 5;
}
This does not make the object itself threadsafe in any way however. there is nothing threadsafe about this collection:
class Foo {
// You still need to take a lock before writing to this list and probably while reading from it
public static readonly List<Int> myList = new List<Int>;
}
Upvotes: 1
Reputation: 283634
Static constructors are (mostly) thread-safe because the runtime takes a lock before running them, thereby providing synchronization. Re-entrancy is still a problem, though.
As far as "static fields generally considered threadsafe", I can only offer that the general wisdom comes from a handful of idiots who got teaching jobs because they couldn't get a job as a professional developer, and now passed on that idiocy to a bunch of students who never had a chance to learn better.
Upvotes: 1
Reputation: 44288
I think you are getting confused, those 'tricks' are not about threading, but avoiding initialization by threads. So if something is initilized when the app loads, you don't have to worry about threads having to intialize things when they first ask for the resource, and hence avoid the race condition of which thread gets there first
Upvotes: 11