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 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 ...

Get Java Projects - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.