volatile keyword in Java
Defining a variable with the volatile keyword means that the value of that variable can be changed by other threads. To understand what volatile does, it is helpful to understand how threads handle regular variables.
For performance reasons, the Java language specification allows the JRE to store a local copy of the variable for each thread that references it. These "local" copies of variables are like a cache and help a thread avoid accessing main memory every time it needs to retrieve the value of a variable. When two threads start, one of them reads variable A as 10, and the other as 20. If the value of variable A has changed from 10 to 20, then the first thread will not know about the change and will store the wrong value A. But if variable A is marked as volatile, then whenever the thread reads the value of A, it will access the master copy of A and read its current value. A thread-local cache makes sense if the variables in your applications will not be changed externally.
If a variable is declared volatile, it means that it can be changed by different threads. It is natural to expect the JRE to provide some form of synchronization for such volatile variables. The JRE does implicitly provide synchronization when accessing volatile variables, but with one very big caveat: reading a volatile variable and writing to a volatile variable are synchronized, but non-atomic operations are not.
The volatile modifier provides atomic reads and writes, and the Atomic* classes (from java.util.concurrent.atomic) allow compare-and-swap operations to atomically change values without fear of another write coming in between reads and writes.
Read also:
Comments
Post a Comment