In a multithread program if we have a static variable then does each thread have its own copy of the variable and is the change made by one thread visible to the other in case of static variable ?? Please explain
5 Answers
All variables1 are shared between all threads.
Only code visibility is defined by the variable type (eg. static/member, public/private) - but not thread visibility. (The volatile modifier affects thread access but is often not sufficient by itself.)
Using correct synchronization (and/or volatile variables) is required for "thread-safe" access for variables, and all data that can be reached from such, that can be accessed by multiple threads. Without correct synchronization there is no guarantee that another thread will 'see' a change to a [static] variable.
1 It is possible to create ThreadLocal 'variables' (via an indirect object), but this should be a rare case.

- 60,010
- 15
- 145
- 220
-
1All variables except local variables and method parameters of course. – Dawood ibn Kareem Apr 12 '15 at 05:18
In a multithread program if we have a static variable then does each thread have its own copy of the variable
No. If you need that, you can use a ThreadLocal
and is the change made by one thread visible to the other in case of static variable
Not immediately. Another thread might still have the old value cached. To guarantee that the change is visible to other threads, you have multiple options. You can use a lock, a synchronized
block/method, make the variable volatile
or use some existing thread-safe utility class like AtomicReference
.

- 1,148
- 8
- 17
If multiple threads are accessing the same static variable, all threads can see the changes.
As a result, if multiple threads are accessing the same variable, you will need to use locks for the variable to be thread-safe.

- 467
- 5
- 12
Yes, Static variables are shared between threads unlike local variables. For more reference : http://java67.blogspot.com/2012/11/what-is-static-class-variable-method.html

- 9
- 2
-
@suseika The essential parts of the answer are already here. Just what is your comment getting at? This is not a link-only answer. In my opinion, this is actually the best answer that's currently here. – Dawood ibn Kareem Apr 12 '15 at 18:49
There is a classic example ----Producers and Consumers. This inspires us that ,if you want to find the variable's change in other thread ,you must consider each Thread's possession time in CPU. EX: The variable may be just changed in one thread,and the other thread don't hava the use of CPU.So it can't find the change. Of course,you can use
synchronized
to limit the thread's behavior(when multithreading) that changes the static variable.But you must know cross use of CPU , that means you don't know multiple threads' running way if you don't define their priority clearly.

- 89
- 6