The volatile keyword only works well when the value of the shared variable is only modified by one thread. If the variable is modified by multiple threads, the volatile keyword doesn't protect you from possible data-race conditions. It also doesn't make operations, such as + or -, atomic. For example, the ++ operator over a volatile variable is not thread-safe.
Since Java 5, Java Memory Model has a happens--before guarantee established with the volatile keyword. This fact has two implications:
- When you modify a volatile variable, its value is sent to the main memory. The value of all the variables modified previously by the same thread are sent too.
- Compilers can't reorder sentences that modify a volatile variable for an ...