0

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();
}
folkboat
  • 167
  • 1
  • 7
  • This is about how `void` methods work. When you call `foo()` the compiler translates it as everything which is in it. In this case, when you call foo() it is like you are calling `x = 42`. – Omid.N May 14 '20 at 05:56

1 Answers1

3

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.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • Thanks! But how is this be implemented? Is this a static feature that the compiler can find all the write operations before the volatile write operation and makes them also visiable. In this case, `x` is visiable just after it is assigned. Or is this a dynamic feature that the Thread can log all the operations it has made, and when it overcomes a volatile write, it then makes all operations above also visiable to other thread. In this case, `x` is guaranteed visiable only after `v = true` is executed. – folkboat May 14 '20 at 06:28
  • 2
    How it is implemented depends on the jvm. Usually using a memory barrier. Sometimes jvm can avoid that but I suppose it cannot in this case – Burak Serdar May 14 '20 at 06:39
  • 1
    @folkboat Check out [§17.4-§17.4.5](https://docs.oracle.com/javase/specs/jls/se14/html/jls-17.html#jls-17.4) of the _Java Language Specification_. – Slaw May 14 '20 at 07:32