public class Volatile {
volatile int x = 0;
public static void main(String a[]) {
Volatile y = new Volatile();
test t1 = new test(y);
test t2 = new test(y);
t1.setName("A");
t2.setName("B");
t1.start();
t2.start();
}
}
class test extends Thread {
Volatile v;
test(Volatile v) {
this.v = v;
}
@Override
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println(Thread.currentThread().getName() + "Says Before " + v.x);
v.x++;
System.out.println(Thread.currentThread().getName() + "Says After " + v.x);
}
}
}
Output
ASays Before 0
BSays Before 0
BSays After 2
BSays Before 2
BSays After 3
ASays After 1 <--- Is it a cache value ?
BSays Before 3
ASays Before 3
BSays After 4
BSays Before 5
BSays After 6
ASays After 5 <--- Is it a cache value ?
ASays Before 6
ASays After 7
ASays Before 7
ASays After 8
Everywhere, I found common point about volatile
guaranteeing that it will not be cached and that different threads will see the updated value
But, from my above example, threads have different values (old/cache values) or is it because of improper implementation ?