At work today, I came across the volatile
keyword in Java. Not being very familiar with it, I found this explanation.
Given the detail in which that arti
From oracle documentation page, the need for volatile variable arises to fix memory consistency issues:
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. 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.
As explained in Peter Parker
answer, in absence of volatile
modifier, each thread's stack may have their own copy of variable. By making the variable as volatile
, memory consistency issues have been fixed.
Have a look at jenkov tutorial page for better understanding.
Have a look at related SE question for some more details on volatile & use cases to use volatile:
Difference between volatile and synchronized in Java
One practical use case:
You have many threads, which need to print current time in a particular format for example : java.text.SimpleDateFormat("HH-mm-ss")
. Yon can have one class, which converts current time into SimpleDateFormat
and updated the variable for every one second. All other threads can simply use this volatile variable to print current time in log files.