Java Instruction Reordering Example Not Working

久未见 提交于 2019-12-11 02:58:56

问题


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:


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.



来源:https://stackoverflow.com/questions/52647427/java-instruction-reordering-example-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!