Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Static classes thread safe

I have gone through msdn where it is written that all the static classes are thread safe. Well that article is meant for version 1.1...

http://msdn.microsoft.com/en-us/library/d11h6832(v=vs.71).aspx

All public static members (methods, properties, fields, and events) within the .NET Framework support concurrent access within a multithreaded environment. Therefore, any .NET Framework static member can be simultaneously invoked from two threads without encountering race conditions, deadlocks, or crashes.

like image 370
slash shogdhe Avatar asked Apr 30 '11 06:04

slash shogdhe


People also ask

Are static thread safe?

Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process.

Can a static class be thread safe C#?

No, it doesn't say that static classes are thread safe, it says that public static members are thread safe. For static methods for example, this means that they only use the data that you send in as parameters, or other static members that are also thread safe.

Is static inner class thread safe?

static methods and inner classes don't have any access to the variables of their dynamic counter part, and consequently can't use monitors/synchronize on an instance of their parent class. Of course this doesn't mean that declaring them and using them is inherently non-thread safe.

Is static field thread safe in Java?

Unlike local variables, static fields and methods are NOT thread safe in Java.


1 Answers

What this is saying that all static members within .NET framework are designed in a thread safe way. That means that all the static methods / fields / properties developed by Microsoft for the .NET Framework. If you want to use a static member provided by .NET Framework itself, then you can assume it's thread safe and use it as such. I would still be suspicious of the validity of that statement though, and assume non-thread safety until proven otherwise.

Any classes that you write (static, or not) yourself and that have static members might or might not be thread safe depending on how you write them. It will not magically be thread safe just because it is a static method/class.

Also take a look at this to understand what are static members and what are static classes:

Static Classes and Static Members

like image 192
Can Gencer Avatar answered Oct 20 '22 14:10

Can Gencer