Volatile variables and their semantics in C/C++ vs Java
In C/C++, volatile variables are to prevent compilers from performing optimizations that may falsify the semantics of the code.
For example:
x=0;
while (x!=0) ;
In the above piece of code, an optimizing compiler can translate the program into
x=0;
while (true) ;
However, this optimization is dangerous because x might be changed by other threads. Making x "volatile" will prevent such an optimization.
(Ref http://en.wikipedia.org/wiki/Volatile_variable)
In contrast, volatile keywords in Java help maintain orderings (happen-before relationships) of accesses to variables. Basically, each java threads are supposed to maintain their own "local" copy of the "main" memory and they only update the "main" memory when needed for efficiency. Therefore, different threads may have different views about a variable. Therefore, in order to ensure consistency, volatile keyword can be used to force a flush every time a thread accesses a volatile variable. As a result, the value of the variable in the "main" memory is always up-to-date. This means that all threads accessing a volatile variable have a consistent view of its value.
There are main differences between volatile and synchronized keywords. A volatile only synchronizes on its own value. When a thread accesses a volatile variable, only its value is flushed to the main memory. However, a synchronized synchronizes values of all variables in the thread's local memory. When a thread access a synchronized region (either a method or a block of code), it flushes all variables in its local memory.Therefore, synchronized incurs more overhead than volatile.
(Ref http://www.javaperformancetuning.com/news/qotm030.shtml)
Labels: C/C++, java, synchronized, volatile