This question already has answers here:
Are static variables shared between threads?
(7 answers)
Closed 7 years ago.
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
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.
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.
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.
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
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.
Related
This question already has answers here:
When and how should I use a ThreadLocal variable?
(26 answers)
Closed 5 years ago.
I am trying to understand the concept of ThreadLocal concept in Java and I am bit confused.
For example, to define the task of thread we do like this:
public void run() {
int sum = 0;
// Code which a thread executes
}
So, if we created say 6 threads, won't each thread have its own "sum" variable as local?
If this is not the concept of ThreadLocal, am i missing something in understand this concept.
Can anyone help me understand this?
Local variables within a method are always local to the thread, as they live on the stack. However, instance variables of the class implementing the thread live on the heap and are shared by all threads.
If each thread needs its own copy you need to use ThreadLocal, which under the covers is just a Map<key-class,value-class> where the key is the thread identifier and the value is the thread-local value itself.
Consider a single instance of a class that can be used by multiple threads. Note, I'm NOT referring to the Runnable itself, but to an instance whose methods can be invoked from several different threads. There is a single instance and the class is designed to be used by multiple threads in parallel. So it needs to keep each calling thread's state separate from other threads' state. This is the use case for ThreadLocal.
sum is not a ThreadLocal variable.
ThreadLocal is an instrument which allows storing values on per-thread basis. Please see the following question for more details:
When and how should I use a ThreadLocal variable?
Consider the following code:
ThreadLocal<Integer> sum = new ThreadLocal();
sum.set(15);
Then, when you call sum.get(), you'll get 15 in the thread where you called sum.set(...) and null in other threads.
ThreadLocal achieves it by maintaining a static map of thread/value.
Is it safe to say that a ThreadLocal variable is conceptually the 'opposite' of a volatile variable in Java?
Because in the former, every thread will only read/updatea local copy of the variable. But in the latter, every thread will always see the latest value of the variable that is in main memory....no chance of seeing stale values.
Exactly but with a slight twist,
a ThreadLocal variable is a variable different for each thread
any other variable exists only once so common for each Thread using the same object, whether it is volatile or not.
Volatile however specifies some kind of thread read/write boundary so they must synchronize on the latest value written by any other thread. However using volatile does not ensure thread safety.
E.g. a increment method incrementing a volatile int might still generate duplicates. To be sure that works thread safe you must synchronize the method updating the volatile attributes!
check this for more detailed information: https://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When exactly do you use the volatile keyword in Java?
When and why volatile modifier is required in java?
I am interested in seeing a real world usage of a volatile modified primitive or object reference.
volatile modifier will tell the JVM to be cautious of the threads which runs concurrently. Essentially, volatile is used to indicate that a variable's value will be modified by different threads.
Declaring a volatile Java variable means:
The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory"
Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.
We say "acts as though" in the second point, because to the programmer at least (and probably in most JVM implementations) there is no actual lock object involved.
The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program. One of these situations involves multithreaded programs.
In a multithreaded program, sometimes, two or more threads share the same instance variable. For efficiency considerations, each thread can keep its own, private copy of such a shared variable.
The real (or master) copy of the variable is updated at various times, such as when a synchronized method is entered. While this approach works fine, it may be inefficient at times. In some cases, all that really matters is that the master copy of a variable always reflects its current state.
To ensure this, simply specify the variable as volatile, which tells the compiler that it must always use the master copy of a volatile variable (or, at least, always keep any private copies up to date with the master copy, and vice versa). Also, accesses to the master variable must be executed in the precise order in which they are executed on any private copy.
If you are working with the multi-threaded programming, the volatile keyword will be more useful. When multiple
threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it’s
updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which
is using the same variable doesn’t know anything about the values changed by the another thread. To avoid this problem,
if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the
values, it is updated to the main memory. So, other threads can access the updated value.
Declaring a variable volatile means
There will be no cache maintained means all the changes made in main memory.
Access to this variable acts as synchronized block, even though it is in synchronized unit.
Example -
public class Snippet implements Runnable{
volatile int num =0;
public void run(){
Thread t = Thread.currentThread();
String name = t.getName();
if(name.equals("Thread1")){
num=10;
}
else{
System.out.println("value of num is :"+num);
}
}
public static void main(String args[]) throws InterruptedException{
Runnable r = new Snippet();
Thread t1 = new Thread(r);
t1.setName("Thread1");
t1.start();
Thread.sleep(1000);
Thread t2 = new Thread(r);
t2.setName("Thread2");
t2.start();
}
}
(This answer assumes Java 5+ -- before that, volatile had weaker guarantees.)
It's useful when you want to ensure a memory barrier, aka a formal "happens-before" relationship, between a write to a field and a subsequent read to that field by a separate thread. Synchronization can also give you that relationship, as well as other multithreading guarantees, but it's a tad slower and can create synchronization bottlenecks.
One use case is in concurrent collection classes (like ConcurrentHashMap, or LinkedBlockingQueue) where, in conjunction with things like atomic compare-and-set (CAS) operations, you can write correct thread-safe code without having to use synchronized.
You got good answers for the first question. The second one:
Can any one give me real time scenario of it
IMO, you should never ever you volatile. There are better tools for multithreaded apps. It's a bit bizarre that such a high level language has this keyword. Here is a good read (It's about C#, but Java is similar in this matter).
In Java, when we want to ensure that compiler should not do optimization by keeping a local copy of a variable, then we make the variable volatile. Using the variable as volatile ensures that the threads would not use a local copy of the variable but they would use the variable as it is stored in the main memory. But, does it mean that the volatile variable is thread-safe? Also how does it differ in case of a primitive type and in case we use a user defined object?
volatile means that the value will always be fresh; if another thread put a new object into the variable before you, you will see that object.
It does not change the behavior of the value; you cannot magically make an object thread-safe.
not at all,in fact,volatile means that's the value can be seen by another thread at once, but don't mean that it's thread safe, it's not thread safe.
you can see this: http://java.sun.com/docs/books/jls/third_edition/html/classes.html and find the keyworkd volatile Fields
another refer here : http://www.ibm.com/developerworks/java/library/j-jtp06197/index.html
volatile variable ensures visiblity and is not atomic.
Volatile is usually most appropriate for 'simple' state. Ex. a boolean member variable that may be set to tell a worker thread to terminate.
value of volatile variable will never be stored thread locally.
all reads and writes go to main memory.
meaning of volatile is different depending on the version of Java (i.e till Java 1.4 and after Java5.0).
one more link about volatile
When to use volatile keyword vs synchronization in multithreading?
Use volatile to guarantee that each read access to a variable will see the latest value written to that variable. Use synchronized whenever you need values to be stable for multiple instructions. (Note that this does not necessarily mean multiple statements; the single statement:
var++; // NOT thread safe!
is not thread-safe even if var is declared volatile. You need to do this:
synchronized(LOCK_OBJECT){var++;}
See here for a nice summary of this issue.
Volatile only ensures the read operation always gives the latest state from memory across threads. However, it does not ensure any write safety / ordering of operations, i.e. two threads can update the volatile variable in any random order. Also it does not ensure that multiple operations on the variable are atomic.
However a synchronized block ensures latest state and write safety. Also the access and update to variable is atomic inside a synchronized block.
The above, however is true, only if all the access / updates to the variable in question are using the same lock object so that at no time multiple threads gets access to the variable.
That's a pretty broad question. The best answer I can give is to use synchronized when performing multiple actions that must be seen by other threads as occurring atomically—either all or none of the steps have occurred.
For a single action, volatile may be sufficient; it acts as a memory barrier to ensure visibility of the change to other threads.