Search code examples
javavisibilityatomicvolatile

Visibility guarantees of atomic variables


Having read lots about volatile, atomic and visibility, one question remains. Following works across threads, "a" is visible all the time, when "b" is updated/read:

int a;
volatile int b;
a = 1; b = 1;
...
// different thread
if (b == 1) // do something with a, which is 1 now

Does the same hold true with atomic variables, which are separate objects, will the following work?

int a;
AtomicInteger b = new AtomicInteger();
a = 1; b.set(1);
...
// different thread
if (b.get() == 1) // a guaranteed to be 1 here all the time ???

If the answer is no, then it should work to extend the AtomicInteger class and include "a" within there, because AtomicInteger wraps a volatile.


Solution

  • A get() is equivalent to reading from a volatile variable, and a set() is equivalent to writing to it. We have a happens-before relationship here write -> read and therefore, "a guaranteed to be 1 here all the time". This of course is in the context of only these two threads executing.