[jmm-dev] weakCompareAndSet memory semantics

Aleksey Shipilev aleksey.shipilev at oracle.com
Wed Apr 20 09:55:08 UTC 2016


In VarHandles, and relevant intrinsics, we have:
  weakCompareAndSet (relaxed!)

Which means we miss the "volatile" form, or in other words, the
sequentially consistent version. While this is consistent with the rest
of java.util.concurrent, which does not advertise memory effects for
weakCAS: "Additionally weakCompareAndSet does not provide ordering
guarantees that are usually needed for synchronization control."


...I see this deviates from C++11-ish compare_exchange_weak that
defaults to memory_order_seq_cst. I think this deviation breaks
replacing compareAndSet in busy loops with weakCompareAndSet, to benefit
the platforms where CAS is emulated with LL/SC that can spuriously fail.

void incr() {
  int v;
  do {
    v = ai.get();
  } while (!compareAndSet(v, v + 1)); // loop inside for LL/SC

void incr() {
  int v;
  do {
    v = ai.get();
  } while (!weakCompareAndSet(v, v + 1)); // single LL/SC

I wonder if that was the intended use for weakCAS in C++11, and if so,
shouldn't we re-spec weakCAS in Java to have volatile/seq_cst memory


More information about the jmm-dev mailing list