After Googling a lot, I found multiple definitions for volatile keyword.
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.
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?
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 -
volatileis 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),
volatileis not enough; instead, you can use: