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
There are two different uses of volatile keyword.
Prevents JVM from reading values in register, and forces its value to be read from memory.
A busy flag is used to prevent a thread from continuing while the device is busy and the flag is not protected by a lock:
while (busy) {
/* do something else */
}
The testing thread will continue when another thread turns off the busy flag:
busy = 0;
However, since busy is accessed frequently in the testing thread, the JVM may optimize the test by placing the value of busy in a register, then test the contents of the register without reading the value of busy in memory before every test. The testing thread would never see busy change and the other thread would only change the value of busy in memory, resulting in deadlock. Declaring the busy flag as volatile forces its value to be read before each test.
Reduces the risk of memory consistency errors.
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.
The technique of reading, writing without memory consistency errors is called atomic action.
An atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete.
Below are actions you can specify that are atomic:
Cheers!