I was wondering when declaring a class variable (i.e. a variable declared outside a method) would potentially cause problems in a program that's executed by several threads. I suppose final
s are save to use (i.e. not shared), and static
variables are definitely shared between threads. But what about "standard" variables? When are they shared and when are they "private" to each individual thread?
Update: While I accept that local variables (within methods) are not shared and class variables usually are I would love to understand why that is (from a technical point of view). So any explanation to that effect (or links to articles that are fairly easy to understand) would be much appreciated.
Java provides the ThreadLocal<T>
class to declare variables that are not shared between threads. Non-final
parameters and local variables are also not shared between threads. final
parameters and locals variables may be shared between threads when they are used in an anonymous class definition, but this shouldn't be a problem since they are final
. In all other cases I can think of, variables can be shared between threads.
The short answer is, any method or variable, both static
and non-static
, has the potential to be accessed by more than one Thread
if its access modifier makes it visible to that Thread
.
The concept of "thread-safe" is entirely different. If a variable is read-only (final
can be used to make primitives read-only, but only makes references to objects immutable, not the objects themselves), multi-threaded access of that variable is inherently thread-safe. If it can be written to, the proper use of synchronized
blocks or the volatile
keyword is necessary to ensure mutual exclusion.
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