Java Volatile Variable

Bala

I am trying to understand volatile usage by the below example. I expect it to print 10 first and then 15 second. But most of the time i end getting 10 and 10. Is some thing with the below code itself.

class T implements Runnable {

    private volatile int x = 10;

    @Override
    public void run() {
        if(x==10) {
            System.out.println(x);
            x = x+ 5;
        } else if(x==15) {
            System.out.println(x);
        }
    }
}


public class Prep {

    public static void main(String [] args) {
        T t1 = new T();
        new Thread(t1).start();
        new Thread(t1).start();
    }
}
JB Nizet

You just have a race condition: both threads run in parallel, and thus you have (for example)

  • thread 1 tests if x == 10 (true)
  • thread 2 tests if x == 10 (true)
  • thread 1 prints 10
  • thread 2 prints 10
  • ...

The fact that x is volatile here is irrelevant. The only thing that volatile guarantees in this example is that if thread 1 has already incremented x when thread 2 reads its value, then thread 2 will see the incremented value. But it doesn't mean that the two threads can't run in parallel as shown above.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related