What is volatile keyword - Use of volatile variable
- The volatile keyword tells the JVM that a thread accessing the variable must always reconcile its own private copy of the variable with the master copy in memory.
- Volatile variables ensure that updates to a variable are propagated predictably to other threads.
- When a field is declared volatile, the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations.
- Volatile variables are not cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always returns the most recent write by any thread.
- The visibility effects of volatile variables extend beyond the value of the volatile variable itself.
- When thread A writes to a volatile variable and subsequently thread B reads that same variable, the values of all variables that were visible to A prior to writing to the volatile variable become visible to B after reading the volatile variable.
- So from a memory visibility perspective, writing a volatile variable is like exiting a synchronized block and reading a volatile variable is like entering a synchronized block. However, we do not recommend relying too heavily on volatile variables for visibility; code that relies on volatile variables for visibility of arbitrary state is more fragile and harder to understand than code that uses locking.
- Use volatile variables only when they simplify implementing and verifying your synchronization policy; avoid using volatile variables when verifying correctness would require subtle reasoning about visibility.
- Good uses of volatile variables include ensuring the visibility of their own state, that of the object they refer to, or indicating that an important lifecycle event (such as initialization or shutdown) has occurred.
Volatile variables limitations
- The most common use for volatile variables is as a completion, interruption, or status flag, such as the asleep flag.
- Volatile variables can be used for other kinds of state information, but more care is required when attempting this.
- For example, the semantics of volatile are not strong enough to make the increment operation (count++) atomic, unless you can guarantee that the variable is written only from a single thread. (Atomic variables do provide atomic read modify write support and can often be used as "better volatile variables")
You can use volatile variables only when all the following criteria are met
- Writes to the variable do not depend on its current value, or you can ensure that only a single thread ever updates the value.
- Locking is not required for any other reason while the variable is being accessed.