volatile
volatile
The Java volatile keyword is used to mark a Java variable as "being stored in main
memory". More precisely that means, that every read of a volatile variable will be
read from the computer's main memory, and not from the CPU cache, and that
every write to a volatile variable will be written to main memory, and not just to
the CPU cache.
Actually, since Java 5 the volatile keyword guarantees more than just that volatile
variables are written to and read from main memory
In a multithreaded application where the threads operate on non-volatile variables, each thread may copy
variables from main memory into a CPU cache while working on them, for performance reasons. If your
computer contains more than one CPU, each thread may run on a different CPU. That means, that each thread
may copy the variables into the CPU cache of different CPUs. This is illustrated here:
With non-volatile variables there are no guarantees about when the Java Virtual Machine (JVM) reads
data from main memory into CPU caches, or writes data from CPU caches to main memory. This can
cause several problems
public class SaharedObject
{
public int counter=0;
}
If the counter variable is not declared volatile there is no guarantee about when the value of the counter variable
is written from the CPU cache back to main memory
. This means, that the countervariable value in the CPU cache may not be the same as in main memory. This
situation is illustrated here:
The problem with threads not seeing the latest value of a variable because it has not yet been written
back to main memory by another thread, is called a "visibility" problem. The updates of one thread
are not visible to other threads.
So java solves this with volatile keyword.
• if two threads are both reading and writing to a shared variable, then using the volatile keyword for that is not
enough. You need to use a synchronized in that case to guarantee that the reading and writing of the variable is
atomic. Reading or writing a volatile variable does not block threads reading or writing. For this to happen you
must use the synchronized keyword around critical sections.
• In case only one thread reads and writes the value of a volatile variable and other threads only read the variable,
then the reading threads are guaranteed to see the latest value written to the volatile variable. Without making the
variable volatile, this would not be guaranteed.
• As an alternative to a synchronized block you could also use one of the many atomic data types found in
the java.util.concurrent package. For instance, the AtomicLong or one of the others.