[concurrency-interest] Difference between AtomicReference.getPlain() and getOpaque()

Andrew Haley aph at redhat.com
Sun Oct 15 04:52:01 EDT 2017

On 15/10/17 09:38, Florian Weimer wrote:
> Are these methods essentially the same?  I think so, based on JLS ยง17.7:
> | Writes to and reads of references are always atomic, regardless of
> | whether they are implemented as 32-bit or 64-bit values.
> I assume there is a difference between getPlain() and getOpaque() for
> AtomicLong because of potentially non-atomic access: I assume
> getOpaque() rules that out (but that is not very clear), but
> getPlain() obviously does not.

Consider a reference field x, and a loop:

while (x == null) { }

and another thread

x = new Object();

If x is not volatile, Java compiler can hoist the load of x out of a loop
and turn that loop into

for (;;) { }

... so it loops forever.

However, it cannot do the same with getOpaque().  Eventually the read of
x will return non-null, although it may be delayed for a long time and it
won't be ordered with any other accesses.

Andrew Haley
Java Platform Lead Engineer
Red Hat UK Ltd. <https://www.redhat.com>
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671

More information about the Concurrency-interest mailing list