Java Instruction Reordering Example Not Working
Asked Answered
S

1

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;
        }
    }
 }
Simpkins answered 4/10, 2018 at 13:1 Comment(1)
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.Frayda
F
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.

Freddyfredek answered 4/10, 2018 at 13:13 Comment(1)
Got it. So b > a is not atomic. This means that this example is invalid.Simpkins

© 2022 - 2024 — McMap. All rights reserved.