Volatile variables
Let's modify the declaration of the o
variable in our sample code as follows:
private volatile Object o = null;
The preceding code runs fine and stops after a second or so. Any Java implementation has to guarantee that multiple threads can access volatile
fields and the value of the field is consistently updated. This does not mean that volatile declaration will solve all synchronization issues, but guarantees that the different variables and their value change relations are consistent. For example, let's consider we have the following two fields incremented in a method:
private volatile int i=0,j=0; public void method(){ i++; j++; }
In the preceding code, reading i
and j
from another thread will never result an i>j
. Without the volatile declaration, the compiler is free to reorganize the execution of the increment operations if it needs and thus, it will not guarantee that an asynchronous thread reads consistent values.