The java concurrency tutorial states that:
Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
Reads and writes are atomic for all variables declared volatile (including long and double variables).
I created a simple experiment to test this
package experiment0;
public class Experiment0 {
public static int i=9;
public static void main(String[] args) {
i=9;
(new Thread(){
public void run(){
while(i==9){
//System.out.println("i==9");
}
System.out.println("\ni!=9");
}
}).start();
(new Thread(){
public void run(){
try{
Thread.sleep(3000);
i=8;
}catch(Exception e){
}
}
}).start();
}
}
When I run this code the program never gets terminated! In order for it to work I either have to uncomment the line inside the while loop of the first thread or declare i as volatile.
Am I missing something? Is the documentation wrong and should it say that all primitives should be declared as volatiles in these kind of cases? Why does a write to System.out "solve" the problem? Does it give enough time to the second thread to change i?