简体   繁体   中英

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);

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM