'Why the volatile keyword is not effective in this code?
I have used volatile keyword in the below mentioned block of code, expecting that it's updated value will always be read from memory. But the output is not as expected. Please help me to understand what is wrong here.
public class Multithread5 {
public static void main(String[] args){
VolatileData data = new VolatileData();
VolatileDataReader thread1 = new VolatileDataReader(data);
VolatileDataReader thread2 = new VolatileDataReader(data);
thread1.start();
thread2.start();
}
}
class VolatileData{
private volatile int counter = 0;
public void increase(){
this.counter++;
}
public int getCounter(){
return this.counter;
}
}
class VolatileDataReader extends Thread{
private VolatileData volatileData;
VolatileDataReader(VolatileData volatileData){
this.volatileData = volatileData;
}
public void run(){
int volatileData = this.volatileData.getCounter();
System.out.println("Volatile Data:"+volatileData);
this.volatileData.increase();
volatileData = this.volatileData.getCounter();
System.out.println("Volatile Data after increase:"+volatileData);
}
}
Output:
Volatile Data:0
Volatile Data:0
Volatile Data after increase:1
Volatile Data after increase:2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
