Reputation: 2095
I have an volatile variable example :
public class VolatileTest {
private static volatile int MY_INT1 = 0;
public static void main(String[] args) {
new ChangeListener().start();
new ChangeMaker().start();
}
static class ChangeListener extends Thread {
@Override
public void run() {
int local_value = MY_INT1;
while ( local_value < 5){
if( local_value!= MY_INT1){
System.out.println("Got Change for MY_INT1 "+ MY_INT1);
local_value= MY_INT1;
}
}
}
}
static class ChangeMaker extends Thread{
@Override
public void run() {
int local_value = MY_INT1;
while (MY_INT1 <5){
System.out.println("Incrementing MY_INT1 to "+ (local_value+1));
MY_INT1 = ++local_value;
}
}
}
}
Now when I run it , I get output like below :
Incrementing MY_INT1 to 1
Incrementing MY_INT1 to 2
Incrementing MY_INT1 to 3
Incrementing MY_INT1 to 4
Incrementing MY_INT1 to 5
Got Change for MY_INT1 2
This output is variable but my concerns is that when the change listener is printing the value(in this case, it happened in last line) then it should be the latest value which is 5 and in this case it is 2 which is older value. So what went wrong here?
Upvotes: 0
Views: 156
Reputation: 1819
volatile
sort the instructions that are performed over the variable, while synchronization is about to get exclusive access to the variable (or code).
Since the program printed Got Change for MY_INT1 2
until it executed local_value= MY_INT1;
, MY_INT1
was updated 3 times by ChangeMaker
.
If you want the right output, synchronize the access to MY_INT1
in ChangeListener
Upvotes: 1