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
Related
I have two threads sharing the same variable of type boolean. I discovered that I have to use volatile to guarantee the value is always read from main memory. But now I want to get rid of this volatile identifier, how can I achieve that? Is it true that I easily can extract my boolean property into an object. As the reference to object never change the thread will always access the correct value from the main memory. Will this work?
I have to use volatile to guarantee the value is always read from
main memory
That is not how volatile work. volatile is used to build a happens-before relation ship:
This means that changes to a volatile variable are always visible to
other threads. What's more, it also means that when a thread reads a
volatile variable, it sees not just the latest change to the volatile,
but also the side effects of the code that led up the change.
—— From the doc.
But now I want to get rid of this volatile identifier, how can I
achieve that?
Like said in another answer, you can use AtomicBoolean. Or, add synchronized block around the code reading/writing this variable. Or use some other mechanism, as well as they can build a happens-before relation ship between reading and writing this varibale in different threads.
Is it true that I easily can extract my boolean property into an
object. As the reference to object never change the thread will always
access the correct value from the main memory. Will this work?
No. The reference do not change, this does not mean the fresh object is always visible to other reading threads after it is updated.
you can also use AtomicBoolean instead if you do not like the keyword - also this will allow write access to be thread safe too
If I have multiple threads accessing the same global variable, each thread can cache the value of this variable, and access this cached copy from now on. I can use volatile to prevent this from happening, for example:
volatile int i = 123;
My question is: what does this behavior called (the behavior that each thread creates its own "copy" of the variable)?
You could call it code optimisation, cpu optimisation, compiler optimisation. Using volatile also provides happens-before and happens-after guarantees.
Note: this optimisation can be done by the javac, the JIT or the CPU.
Esentially, 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.
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
Say that I have a private variable and I have a setVariable() method for it which is synchronized, isn't it exactly the same as using volatile modifier?
No. Volatile means the variable isn't cached in any per-thread cache, and its value is always retrieved from main memory when needed. Synchronization means that those per-thread caches will be kept in sync at certain points. In theory, using a volatile variable can come with a great speed penalty if many threads need to read the value of the variable, but it is changed only rarely.
No, calling a synchronized getXXX/setXXX method is not the same as reading/writing to a volatile variable.
Multiple threads can concurrently read from or write to a volatile variable. But only one thread at a time can read from or write to a variable that is guarded by a synchronized block.
volatile variables are not synchronized (at least, not in the way synchronized stuff is synchronized). What volatile does is ensure that a variable is retrieved each time it's used (ie: it prevents certain kinds of optimization), and IIRC that it's read and written in the correct order. This could conceivably emulate some kinds of synchronization, but it can't work the same if your setter has to set more than one thing. (If you set two volatile variables, for example, there will be a point where one is set and the other isn't.)
Actually No.
volatile is actually weaker form of synchronization, when field is declared as a volatile the compiler and runtime understands that this variable is shared and operations on it shouldn't be reordered with other memory operations. Volatile variable aren't cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always return a recent write by any thread.
just an example :
First thread run :
while(stopped){
... do something
}
Second thread run :
stopped = true;
it's useful to declare stopped as a volatile boolean for the first thread to have a fresh value of it.
There is no any relation.
Basically
Volatile => it always retrieves parameter's latest value
Synchronized => it serves only 1 thread at the same time