I am learning volatile variable. I know what volatile does, i wrote a sample program for Volatile variable but not working as expected.
Why the program is going in infinite loop? If the variable "isTrue" is volatile then it should always get the value from Main memory? why the thread is caching it?
Can someone please explain why? and also if can provide the solution for that...(I will not put isTrue in while loop)
I have one VolatileSample class as:-
public class VolatileSample{
static volatile boolean isTrue=true;
public VolatileSample(boolean is){
isTrue=is;
}
public void print() {
boolean b=isTrue;
while (b) {
System.out.println("In loop!");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void setFalse() {
boolean b=false;
System.out.println("Setting value as false");
isTrue=b;
}
}
Created two threads as:-
public class Thread1 extends Thread{
VolatileSample sample;
public Thread1(VolatileSample sample){
this.sample=sample;
}
public void run(){
sample.print();
}
} And
public class Thread2 extends Thread{
VolatileSample sample;
public Thread2(VolatileSample sample){
this.sample=sample;
}
public void run(){
sample.setFalse();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Main class:-
public class Test {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
VolatileSample sample=new VolatileSample(true);
Thread1 t1=new Thread1(sample);
Thread2 t2=new Thread2(sample);
t1.start();
t2.start();
}
}