3

I am trying to understand the following paragraph about volatile variables in java. (from section 3.1.4 of Java concurrency in practice):

"The visibility effects of volatile variables extend beyond the value of the volatile variable itself. When thread A writes to a volatile variable and subsequently thread B reads that same variable,the values of all variables that were visible to A prior to writing to the volatile variable become visible to B after reading the volatile variable. So from a memory visibility perspective, writing a volatile variable is like exiting a synchronized block and reading a volatile variable is like entering a synchronized block."

Why writing to a volatile variable by A and reading the same variable by B makes other variables visible to B? Is it because volatile acts as a barrier?

Reimeus
  • 158,255
  • 15
  • 216
  • 276
apadana
  • 13,456
  • 15
  • 82
  • 98
  • 2
    Why? Because that's how the effects of volatile are specified, because the Java designers wanted it that way. You can give whatever name you want to this is that makes you more comfortable. But I don't see how we could answer this question. – JB Nizet Nov 11 '14 at 10:05
  • I want to know why that happens in more details. More like a generic description of how compiler/jvm achieves this behavior. I don't understand why writing a single variable makes other variables visible. – apadana Nov 11 '14 at 10:07
  • The semantics of volatile are clear: given a variable, every read and write to it goes straight to RAM instead of local registers or the cache. But what has a single volatile variable to do with the rest of the variables thread A can see? I have no idea. – vz0 Nov 11 '14 at 10:09
  • 1
    @JBNizet It is not really a duplicate - the other asks why the preceding writes would not be visible without volatile - this one asks why they would be visible with volatile. And (!volatile => no visibility) does not imply what the op is asking here, that (volatile => visibility)... – assylias Nov 11 '14 at 10:17
  • @assylias But the answers explain it. Anyway, feel free to vote for reopening. – JB Nizet Nov 11 '14 at 10:20

0 Answers0