Main Functions of volatile keyword -
- Reads and writes are atomic for all variables that are declared
volatile. This includes long and double variables too (irrespective the architecture of the OS x64 or 32 bit)
- Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. 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.
- afterwards Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and non-volatile both).
Please be noted that Atomic actions cannot be interleaved, so they can be used without fear of thread interference.
Using simple atomic variable access is more efficient than accessing these variables through synchronized code, but requires more care by the programmer to avoid memory consistency errors. Whether the extra effort is worthwhile depends on the size and complexity of the application.