Search code examples
javamultithreadingvolatileatomic

Differences between volatile and atomic


int value = 0;
volatile boolean done = false;

// Thread A:
value = 1; done = true;

// Thread B:
if (done) System.out.println(value);

This is fine, since done is defined as volatile.

What about the same code, except that done is defined as an AtomicBoolean - does it achieve the same effect? In other words, do atomic (RMW) operations, apart from being atomic and visible, also guarantee that all previous write are flushed to shared memory?

int value = 0;
AtomicBoolean done = new AtomicBoolean(false);

// Thread A:
value = 1; done.set(true);

// Thread B:
if (done.get()) System.out.println(value);

Solution

  • From the Javadoc of java.util.concurrent:

    The memory effects for accesses and updates of atomics generally follow the rules for volatiles, as stated in The Java Language Specification (17.4 Memory Model):

    • get has the memory effects of reading a volatile variable.
    • set has the memory effects of writing (assigning) a volatile variable.
    • ...

    So in this case, there is no difference between volatile and AtomicBoolean.