Is a static member of a class present as only a single instance per process or thread? Meaning does each thread has its own copy of the static member variable of the class?
My guess is per process, am I correct?
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.
So while thread confinement of an object is a valid thread safety policy for instances of a class, this same reasoning is invalid for static methods because they have no instance.
Final variables are immutable references, so a variable declared final is safe to access from multiple threads. You can only read the variable, not write it. Be careful, because this safety applies only to the variable itself, and we still have to argue that the object the variable points to is immutable.
A data type or static method is threadsafe if it behaves correctly when used from multiple threads, regardless of how those threads are executed, and without demanding additional coordination from the calling code.
Is a static member of a class present as only a single instance per process or thread?
static
fields have one value per class-loader but I think the meat of your question is in the following:
each thread has its own copy of the static member variable of the class
This is correct although the devil is in the details. Each thread may have it's own copy of the field in it's own local memory space/cache unless the field has been marked with volatile
which forces the field to be surrounded with a memory barrier which causes a memory synchronization on each access/update.
Without volatile
, any updates and reads to a static
field will be made to local thread storage and only updated whenever a thread crosses a memory barrier. Without the memory barriers, there are no guarantees around the order of data operations and when the updates will be shared with other threads.
Here's a decent page about the Java memory model and a good overview of some of the challenges.
Static fields gave one value per class-loader.
If you want a per-thread value, make a static ThreadLocal<T>
.
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