0

My understanding of "volatile" have been that changes made to a volatile variable by one thread is visible to another thread (basically all threads see a consistent value of the variable) and that seems to be right as well if I read JLS or other answers.

But when I read answer to this question then I get confused because as per me marking the variable as volatile will ensure that other threads will read the correct value of boolean.

Please correct me if I am missing something.

pjj
  • 2,015
  • 1
  • 17
  • 42
  • Volatile doesn't guarantee atomicity and `bool = !bool;` is not an atomic operation in itself. – Kayaman Feb 14 '18 at 21:06
  • What exactly do you mean by "correct value"? All threads will see the same value at the same time, but since the value changes over time, and the threads may read it at different times, the results may still be unexpected to you. – user4235730 Feb 14 '18 at 21:11
  • @Kayaman: Can I read "Volatile doesn't guarantee atomicity" as "Volatile doesn't guarantee synchronization"? – pjj Feb 14 '18 at 21:21
  • @pjj no you can't, or at least you really shouldn't. Atomic is the key word here, as the term is not related to any specific language. – Kayaman Feb 15 '18 at 06:31

0 Answers0