Take the 2-minute tour ×

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

share|improve this question

2 Answers 2

up vote 11 down vote accepted

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.

share|improve this answer
I don't see how reader is guaranteed see x at 42. Sure the x=42 can happen before v=true, but reader() could still see a cached value of 0, no? –  Shawn Feb 8 '12 at 4:13
@Shawn Until Java-5 that was correct, but Java-5 memory model makes sure that all writes complete before the volatile write. See link for details. –  dasblinkenlight Feb 8 '12 at 4:16
thanks, good to know! –  Shawn Feb 8 '12 at 4:22

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!

share|improve this answer

Your Answer


