1

After some Googling and reading StackOverflow posts, it is not clear to me if marking a variable as volatile makes it thread safe.

Does it?

David Soroko
  • 8,521
  • 2
  • 39
  • 51

1 Answers1

1

In a word - no.

Marking variable as volatile addresses the problem of "safe publishing" where changes made to a variable by one thread are visible by all others (there are other ways of doing this too). There is no such guarantee when a variable is not volatile.

Safe publishing is but one one of the challenges of multi-threaded programming - there are others.

David Soroko
  • 8,521
  • 2
  • 39
  • 51
  • Why changes made to a volatile variable visible to other threads and changes made to non-volatile variables are not? –  Oct 27 '18 at 18:48
  • As an optimization, a variable value may be copied from the main memory onto a CPU/core on which a thread is executing. This is similar to reading a value into memory from disk and manipulate it there instead of constantly reading and writing to disk. When a variable is marked as volatile, whenever a thread performs a read of such variable, it's current value is flushed back to main memory. – David Soroko Oct 27 '18 at 22:07