[jmm-dev] weakCompareAndSet memory semantics

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


Hi,

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

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."

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html

...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
effects?

Thanks,
-Aleksey



More information about the jmm-dev mailing list