Let's say that I have a private variable, and I have a setVariable() method for it that is synchronized , is it not using the volatile ?
setVariable()
synchronized
volatile
Not. Volatile means that the variable is not cached in the cache-cache stream, and its value is always extracted from the main memory if necessary. Synchronization means that these caches for each thread will be synchronized at specific points. Theoretically, using a mutable variable can have a large penalty for speed if many threads need to read the value of a variable, but it rarely changes.
No, calling the synchronized getXXX / setXXX method is not the same as reading / writing to the volatile variable.
Multiple threads can read or write volatile at the same time. But only one thread at a time can read or write a variable that is protected by a synchronized block.
volatile variables are not synchronized (at least not in the way synchronized material is synchronized ). What volatile does ensures that the variable is retrieved each time it is used (i.e. it prevents certain types of optimization), and the IIRC that it reads and writes in the correct order. This may seem to emulate some kind of synchronization, but it may not work the same if your setter needs to install more than one. (If you set two volatile variables, for example, there will be a point at which it is installed, and the other will not.)
Actually No.volatile is actually a weak form of synchronization, when a field is declared as volatile , the compiler and the runtime understand that this variable is shared, and operations with it should not be reordered using other memory operations. A volatile variable is not cached in registers or in caches where they are hidden from other processors, therefore reading a volatile variable always returns a new record by any thread.
variable
just an example:
First thread run : while(stopped){ ... do something } Second thread run : stopped = true;
It is useful to declare it stopped as a volatile boolean so that the first thread has a new value.
There is no relation.
Mostly