Let's say I have an atomic reference to a mutable class type Foo
:
AtomicReference<Foo> foo = new AtomicReference<Foo>(new Foo());
Thread A writes to the Foo
object:
foo.get().write(42);
And thread B reads from the Foo
object:
int x = foo.get().read();
Note that the atomic reference itself is never modified! That is, I do not call foo.set
in my code.
Is thread B guaranteed to observe the value that was last written by thread A?
Is thread B guaranteed to observe the value that was last written by thread A?
No. It would be equivalent to:
volatile Foo foo = new Foo();
foo.write(42);
All writes that happen prior to the initial assignment of foo will be visible after foo is non-null. After that however there is no guarantee on when a thread will see the write of foo.write(42)
to occur.