Vaibhav Vaibhav - 1 year ago 124
Java Question

Volatile Vs Atomic

I read somewhere below line.

Java volatile keyword doesn't means 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
method or block in Java.

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

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

What is the difference between Atomic and volatile keyword?

Answer Source

The effect of the volatile keyword is approximately that each individual read or write operation on that variable is atomic.

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.