Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In java, with my knowledge, volatile variable make a thread reads/writes directly to main CPU (not in cache of each thread), so make its change visibles to other threads.

The thing I don't know is : So, why this work (of volatile) can prevent compiler/CPU reorder statement of code.

thanks :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
558 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here is a very good example illustrating the issue the prohibition on reordering is aimed to address (taken from here):

class VolatileExample {
    int x = 0;
    volatile boolean v = false;
    public void writer() {
        x = 42;
        v = true;
    }
    public void reader() {
        if (v == true) {
            //uses x - guaranteed to see 42.
        }
    }
}

In this example, v is volatile, but x is not. If writer and reader are executed concurrently and the reader sees v set to true, x is guaranteed to be 42. Prior to Java-5, compiler was free to re-order the writes to x and v, so you could see x at zero after you've seen v set to true. This was confusing, and lead to subtle errors. Java-5 memory model addressed this issue by making volatile writes almost equivalent to synchronization.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...