The volatile variable in Java is a special variable which is used to signal (flag) in multi-threads programming. By the volatile keyword, the application ensures that its value should always been read from heap memory and other threads should not be used cached value of marked volatile variable from thread's stack.
When to Use Volatile
- Volatile is most useful for lock-free algorithms. You can mark the variable holding shared fields as volatile when you are not using locking to access that variable and you want changes made by one thread to be visible in another.
- Volatile is used on variables that may be modified simultaneously by other threads.
- To save cost of synchronization as volatile variables are less expensive than synchronization.