[jmm-dev] weakCompareAndSet memory semantics

David Holmes david.holmes at oracle.com
Wed Apr 20 22:44:18 UTC 2016


On 20/04/2016 7:55 PM, Aleksey Shipilev wrote:
> 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.

Side question: why would you replace compareAndSet with 
weakCompareAndSet when that would expose those ll/sc spurious failures?

David
-----

> 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