Are mutations visible through an unmodified atom reference?

Let's say I have an atomic reference to a mutable class type Foo

:

AtomicReference<Foo> foo = new AtomicReference<Foo>(new Foo());

      

Topic A writes the object Foo

:

foo.get().write(42);

      

And stream B is read from the object Foo

:

int x = foo.get().read();

      

Note that the atom reference itself does not change! That is, I do not name it foo.set

in my code.

Is thread B guaranteed to respect the value written by the last thread A?

+3


source to share


2 answers


Is thread B guaranteed to respect the value that was last written to thread A?

Not. This would be equivalent to:



volatile Foo foo = new Foo();
foo.write(42);

      

Any entries that occur before the initial assignment to foo will be visible after foo is non-empty. After that, however, there is no guarantee when the stream will see the record foo.write(42)

.

+3


source


Not.

You can't just make thread X safe by making access to a particular instance of it atomic.



For this to be thread safe, you would need to make the base class itself thread safe, not just access to it.

+1


source







All Articles