Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are class variables in Java shared between threads or not?

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 finals 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.

like image 399
Christian Avatar asked Jun 10 '13 14:06

Christian


2 Answers

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.

like image 63
Sam Harwell Avatar answered Oct 26 '22 23:10

Sam Harwell


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.

like image 20
CodeBlind Avatar answered Oct 26 '22 23:10

CodeBlind