Search code examples
javaconcurrencyvolatile

Java Concurrency - How far can the volatile keyword influence


A common example explains the function of the keyword volatile can be something like this(quoted 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.
        }
    }
}

Since v is volatile, the write operation to v will be "write through" so other threads can see. What's more, x is influenced by v to also behaves like volatile since x is assigned above.

So my question is how far the volatile can influence the operations before it?

Is the influence confined to the function where a volatile attribute is assigned? So in the following case, the x will not has the behaviour of "write through" :

public void foo() {
    x = 42;
}

public void writer() {
    foo();
    v = true;
}

Or is the influence will not be confined and can be propagated to all the operations before in this thread? But this seems a bit impossible considering the following case:

private void foo() {
    x = 42; // x will be written through
}

private void fooWrapper() {
    foo();
}

private void writer() {
    fooWrapper();
    v = true;
}

// invoke this! 
public void writerWrapper() {
    y = 0; // y will be written through
    writer();
}

Solution

  • It establishes a "happened-before" relationship, so within that thread, anything that happened before the volatile write will be visible to other threads. In your last example, even though there are multiple functions involved, they all execute sequentially in the same thread and after the volatile write, all writes before that will be visible.