javavolatile

Volatile Vs Atomic


I read somewhere below line.

Java volatile keyword doesn't mean atomic, its common misconception that after declaring volatile, ++ operation will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.

So what will happen if two threads attack a volatile primitive variable at same time?

Does this mean that whosoever takes lock on it, that will be setting its value first? And if in the meantime, some other thread comes up and reads the old value, while the first thread was changing its value, then will the new thread read its old value?

What is the difference between Atomic and volatile keyword?


Solution

  • The effect of the volatile keyword is approximately that each individual read or write operation on that variable is made atomically visible to all threads.

    Notably, however, an operation that requires more than one read/write -- such as i++, which is equivalent to i = i + 1, which does one read and one write -- is not atomic, since another thread may write to i between the read and the write.

    The Atomic classes, like AtomicInteger and AtomicReference, provide a wider variety of operations atomically, specifically including increment for AtomicInteger.