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 that we have the following two fields incremented in a method:
private int i=0,j=0; public void method(){ i++; j++; }
In the preceding code, reading i and j in a different thread may never result in i>j. Without the volatile declaration, the compiler is free to reorganize the execution of the increment operations and thus...