Volatile keyword Thread Safety

  • A+
Category:Languages

After Googling a lot, I found multiple definitions for volatile keyword.

Concept 1:

Some Website says, it is thread safe, as thread acts on the main memory where volatile keyword is stored and modifies it without pulling it to thread stack space.

Concept 2:

Some says, it is not thread safe, as it causes Thread race condition. As , thread pulls volatile variable to stack space , modifies it and immediately puts it back to main memory. But, in between another thread can come and act upon the volatile variable and takes action. So, this way, some value gets missing.

Which concept is correct?

Thanks,

 


volatile is neither thread-safe nor non-thread-safe on its own.

volatile guarantees atomicity for a single field, and so it can be used for single thread-safe reads or single thread-safe writes.

However, if you want to perform a thread-safe operation consisting of a read followed by a write (understood as a whole), volatile alone does not provide thread safety here because volatile guarantees atomicity only to single operations (either read or write).

To sum up:

  • if you have a field and you want to make sure that if one thread writes to it, other threads can immediately read the written value - volatile is enough (without volatile, other threads may never even see the written value)
  • if you have a field that you need to first read and only then write (based on the value you just read so no operations on this value may happen in between), volatile is not enough; instead, you can use:

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: