Volatile variables and other variables

后端 未结 2 1832
旧时难觅i
旧时难觅i 2020-12-05 08:30

The following is from classical Concurency in Practice:

When thread A writes to a volatile variable and subsequently thread B reads t

相关标签:
2条回答
  • 2020-12-05 08:49

    The answer to your question is in JLS #17.4.5:

    A write to a volatile field (§8.3.1.4) happens-before every subsequent read of that field.

    So if in one thread you have

    aNonVolatileVariable = 2 //w1
    aVolatileVariable = 5 //w2
    

    And subsequently in another thread:

    someVariable = aVolatileVariable //r1
    anotherOne = aNonVolatileVariable //r2
    

    You have the guarantee that anotherOne will be equal to 2, even if that variable is not volatile. So yes, using volatile also has side-effects to the usage of non-volatile variables.

    In more details, this is due to 2 other guarantees provided by the Java Memory Model (JMM) in that same section: intra thread order and transitivity (hb(x,y) means x happens before y):

    If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
    [...]
    If hb(x, y) and hb(y, z), then hb(x, z).

    In my example:

    • hb(w1, w2) and hb(r1, r2) (intra thread semantics)
    • hb(w2, r1) because of the volatile guarantee

    so you can conclude that hb(w1, r2) by transitivity.

    And the JMM guarantees that all executions of a program will be sequentially consistent (i.e. will look like nothing has been reordered) if it is correctly synchronized with happens-before relationships. So in this specific case, the non-volatile read is guaranteed to see the effect of the non-volatile write.

    0 讨论(0)
  • 2020-12-05 08:55

    It means if you write to ten non-volatile variable and write to a volatile one, all the non-volatile variables must be set before the volatile one.

    If you read the volatile variable and all the non-volatile ones you can be sure that the order won't be swapped around.

    0 讨论(0)
提交回复
热议问题