So we've all seen the Threading notification on MSDN for many available generic objects:
"Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."
My question is, what is it about being an instance variable vs a public static makes it unsafe?
It is because, Servlets create only one instance and multiple threads access it. So in that case Instance Variables are not thread safe.
Static constructors are always thread safe. The runtime guarantees that a static constructor is only called once. So even if a type is called by multiple threads at the same time, the static constructor is always executed one time.
So, in summary, an Instance member is a member that belongs to an Instance of an object (in our example, the objects are c1 , c2 , and c3 ) whereas a static member belongs to the class itself and does not require an instance of an object as was demonstrated by making a call to CloneGenerator.
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. Hence, access to static variable is not thread safe.
This is only true in general.
In general static methods are static because they are not dependant on nor do they access any instance defined data that another thread could also access. In general, the only variables they (a static method) utilizes are variables declared and tied to the static memory of the class the method is implemented in, not to the memory allocated for object -(the instance of the class) created for that object. A static method does not and cannot reference or utilize any such variable. If a method uses this kind of instance data variable, tied to a specific instance, it cannot be static. An Instance method, in contrast, does access some data element (property or field) of the instance.
If, otoh, a static method accesses a static property or field of the class, it is equally non-thread -safe.
There are four conditions needed for a race to be possible.
Nothing inbuilt makes static any more-or-less different (re thread-safety) than instance, except:
This is not true for instance methods:
So in general it is expected that the caller manage thread-safety over instances.
There are exceptions where instances are thread-safe (usually for things that are deeply tied to threading, such as a producer-consumer queue) - but IMO any static member that isn't thread safe is a bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With