Semantics of VarHandle CAS methods

Martin Buchholz martinrb at
Wed Jul 6 04:18:21 UTC 2016

On Thu, Jun 30, 2016 at 10:54 AM, Hans Boehm <hboehm at> wrote:

> > In C++ we have sequential consistency of the single memory location
> holding
> > an atomic (cache coherence).  Should we say something about locations
> > updated via a VarHandle?  If you call weakCompareAndSetAcquire, then the
> > spec says the write is a "plain write", but some kind of cache coherence
> > seems inherent in the idea of a compareAndSet, so the write itself has to
> > be complete and visible.
> I completely agree that we need to be clear about cache coherence, and not
> just for CAS.
> I think a lot of code cares whether these operations are cache coherent or
> not.
> One could argue that the relaxed operations refer to ordinary Java memory
> semantics
> and are thus clearly not cache coherent, unlike memory_order_relaxed in
> C++.
> But I think this also shows up with acquire release as well.  Using
> acquire/release get/set
> everywhere, can I get
> Thread 1:
> x = 1;
> r1 = x (sees 2)
> Thread 2:
> x = 2;
> r1 = x (sees 1)                             ?
> I think this is entirely consistent with happens-before constraints.  But
> it is rather mind-bending,
> in that, no matter what the final value turns out to be after the threads
> join, it will look to one
> thread like the value of x changed twice.  This behavior is disallowed in
> C++, even for
> memory_order_relaxed.

I agree acquire-release allows this.  My intuition is that a release
protects preceding actions and makes them visible ("publishes") to the
reader.  Similarly an acquire protects subsequent actions and makes the
writer's actions visible.  But in the example there are no such actions!
So we're reduced to m_o_relaxed.

Whenever it's not too expensive, we should offer sequential consistency.
C++ provides sequential consistency for atomic operations on a single
location.  Java probably can and should do the same for corresponding
operations.  But what are these corresponding operations?  Any access via a
VarHandle (including plain?) or via a volatile variable?

More information about the core-libs-dev mailing list