[concurrency-interest] Semantics of compareAndSwapX

Andrew Haley aph at redhat.com
Fri Feb 14 08:12:12 EST 2014

On 02/14/2014 11:52 AM, David Holmes wrote:
> Andrew Haley writes:
>> What are the semantics of Unsafe.compareAndSwapX?  The javadoc is
>> rather thin.
> They are the implementation for the associated AtomicX.compareAndSet methods
> and so have to adhere to the specification of those methods. But in terms of
> memory barriers the key factor is that the variables act as volatiles so the
> semantics are of a volatile read combined with a volatile write.

Yes, but is that all?  Several of my examples have the semantics of a
volatile read combined with a volatile write.  However, they are not
the same.

With a globally visible int thing, is

   thing = 1;
   bool ok = AtomicX.compareAndSet(expect, update);

allowed to do

   tmp = AtomicX.loadExclusive();  // Exclusive load with acquire
   thing = 1;
   bool ok = (tmp == update);
   if (ok)
     AtomicX.storeExclusive(update);  // Exclusive store with release


Strict atomicity forbids this, but AFAICS a volatile read combined
with a volatile write does not.


More information about the Concurrency-interest mailing list