Thread value not cached by threads even without volatile?

vickieel

New Member
\[code\]class Counter{ public int i=0; public void increment() { i++; System.out.println("i is "+i); System.out.println("i/=2 executing"); i=i+22; System.out.println("i is (after i+22) "+i); System.out.println("i+=1 executing"); i++; System.out.println("i is (after i++) "+i); } public void decrement() { i--; System.out.println("i is "+i); System.out.println("i*=2 executing"); i=i*2; System.out.println("i is after i*2"+i); System.out.println("i-=1 executing"); i=i-1; System.out.println("i is after i-1 "+i); } public int value() { return i; } }class ThreadA{ public ThreadA(final Counter c) { new Thread(new Runnable(){ public void run() { System.out.println("Thread A trying to increment"); c.increment(); System.out.println("Increment completed "+c.i); } }).start(); }}class ThreadB{ public ThreadB(final Counter c) { new Thread(new Runnable(){ public void run() { System.out.println("Thread B trying to decrement"); c.decrement(); System.out.println("Decrement completed "+c.i); } }).start(); }}class ThreadInterference{ public static void main(String args[]) throws Exception { Counter c=new Counter(); new ThreadA(c); new ThreadB(c); }}\[/code\]In the above code, ThreadA first got access to Counter object and incremented the value along with performing some extra operations. For the very first time ThreadA does not have a cached value of i. But after the execution of i++ (in first line) it will get cache the value. Later on the value is updated and gets 24. According to the program, as the variable i is not volatile so the changes will be done in the local cache of ThreadA,Now when ThreadB accesses the decrement() method the value of i is as updated by ThreadA i.e. 24. How could that be possible?
 
Back
Top