I am trying to understand java volatile and my understanding is that in the attached code there is a possibility of Reader thread not seeing the Writer threads updates made to the sharedData because the counter variable isn't declared volatile. However in multiple runs I have seen that the changes of WriterThread are immediately visible to the ReaderThread even though I am not using volatile with the counter variable. Can some one point out where I am going wrong please?
public class App
{
public static void main( String[] args )
{
SharedData sharedData = new SharedData();
new WriterThread(sharedData, "Writer1").start();;
new ReaderThread(sharedData, "Reader1").start();;
}
}
class SharedData{
public int counter=0;
}
class ReaderThread extends Thread{
private SharedData sharedData;
ReaderThread(SharedData sd , String name){
super(name);
this.sharedData = sd;
}
public void run() {
while(true) {
System.out.println(this.getName() + ": " + sharedData.counter);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class WriterThread extends Thread{
private SharedData sharedData;
WriterThread(SharedData sd , String name){
super(name);
this.sharedData = sd;
}
public void run() {
while(true) {
System.out.println(this.getName() + ": " + ++sharedData.counter);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}