3

I need some help here. I am trying to create an example that shows volatile is needed to protect against instruction re-ordering.

In this example I am trying to show that b > a only if reordering happens and that volatile will prevent it.

The problem is that in every run I get b>a, and I must be missing something idiotic, but I can't see it.

What am I missing here?

public class Example04Reorder extends Thread {
    volatile static int a = 0;
    volatile static int b = 0;
    public static void main(String[] args) throws InterruptedException {
        Example04Reorder t = new Example04Reorder();
        t.start();
        while( true )
        {
            if ( b > a ) // supposedly happens only on reordering
            {
                System.out.println("b was bigger than a");
                System.exit(1);
            }
        }
    }
    public void run() {
        while (true) 
        {
            a = 5;
            b = 4;
            b = 0;
            a = 0;
        }
    }
 }
1
  • 2
    Re, "I am trying to create an example that shows volatile is needed." Just FYI, a multi-threaded program is never guaranteed to behave badly if you don't follow the rules. The Java Language Specification merely allows it to behave badly. That's one reason that writing correct, multi-threaded programs is so hard: You can't prove the program is correct by testing alone. Commented Oct 4, 2018 at 13:39

1 Answer 1

5

There is no issue here. You have two read operations in your comparison operator. And since there is no delay between assignments in second thread they are executed momentarily. So it is possible that first thread got value 4 for b and when in read value for a it was already set to 0. So that is why you get your results.

Sign up to request clarification or add additional context in comments.

1 Comment

Got it. So b > a is not atomic. This means that this example is invalid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.