简体   繁体   中英

Can "b=3" be reordered before "a=2+b" if a is volatile and b is not?

Because ordinary reading and writing after volatile writing does not prohibit reordering, may b=3 in the following code be reordered before a=2+b?

volatile int a = 1;
int b = 2;

private void demo () {
    a = 2 + b;
    b = 3;
}

Not exactly.

The important thing to be aware of is that given two events, two threads can observe those two events in different order.

Since both of these writes are within a single thread, that thread is guaranteed to observe the two writes in the order that they appear. So there's no risk that the statement a = 2 + b will use the about-to-be-set value of b (namely 3) instead of its already-set value (presumably 2, though it can obviously depend on other code that you haven't shown).

This means that a will end up being set to 4, as desired, not to 5.

But other threads can certainly observe these writes out of order; if another thread has System.out.println("a = " + this.a + ", b = " + this.b) , and there's no other synchronization here, then it's absolutely possible for that thread to print a = 1, b = 3 , showing the original value of a but the new value of b .

The sequential semantics of a program can't be violated. Based on your question, I have the impression that the demo method is executed by a single thread and hence the the volatile nature of a is not relevant.

If I simplify your code a bit into individual loads/stores:

r1=b
a=2+r1
b=3

The only possible allowed outcome is a=4,b=3.

Then b=3 and a=2+r1 can be reordered since it doesn't change the outcome. But if b=3 would jump in front of r1=b, then the outcome of this execution would be a=5, b=3. And this is a violation of the sequential semantics of the program.

For more information, see my answer in this post: Why doesn't this example from Java Concurrency in Practice allow reordering

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM