Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Volatile: why prevent compiler reorder code

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 :)

like image 652
hqt Avatar asked Feb 08 '12 03:02

hqt


2 Answers

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.

like image 97
Sergey Kalinichenko Avatar answered Oct 18 '22 23:10

Sergey Kalinichenko


That's just how the language is defined. Informally, marking a variable volatile in Java specifically tells the compiler that it should not reorder statements around it or optimize on its value, since that value might be modified concurrently in another thread. The particular implementation of the JVM is then responsible for respecting this volatile modifier and taking appropriate precautions not to incorrectly optimize the program.

If you'd like more specific details about what language-level guarantees there are to ensure that volatile works correctly, you may want to look at the Java Language Specification's description of the Java memory model, which defines the abstract rules governing thread behavior. It also describes how volatile interacts with these rules.

Hope this helps!

like image 41
templatetypedef Avatar answered Oct 18 '22 21:10

templatetypedef