[concurrency-interest] AtomicReference weakCompareAndSet "Mayfail spuriously"?

Doug Lea dl at cs.oswego.edu
Wed May 17 07:43:24 EDT 2006


Bob Lee wrote:
> On 5/15/06, Doug Lea <dl at cs.oswego.edu> wrote:
>> Yes, this is fine; it is a good example where either the plain or
>> the weak form would work just as well, so you might as well use
>> the weak form.
> 
> Can you please provide an example of when you'd use one or the other?
> 

Thanks to Bill Pugh for reminding me about a second difference
between weakCompareAndSet vs plain compareAndSet, that normally
goes hand-in-hand with the main difference of failure being
uninformative:

A plain compareAndSet has volatile-write memory model semantics, while a
weakCompareAndSet has non-volatile-write memory model semantics.

This mainly means that the visibility of a value written
using weakCompareAndSet does not imply visibility of previous writes by the
thread performing the weakCompareAndSet. This does hold for plain
compareAndSet though. For example

class C { int a; AtomicInteger b = new AtomicInteger(); }
static C c = new C();

Thread 1:
   c.a = 1;
   c.b.compareAndSet(0, 1);

Thread 2;
    if (c.b.get() == 1) assert(c.a == 1);

But if Thread 1 used weakCompareAndSet, the assertion in
Thread 2 need not hold.

This is a little subtle, but is in keeping with the
"uninformativeness" property of weakCompareAndSet.
It implies that weakCompareAndSet is not a good choice for
implementing locks, semaphores, initialization flags, etc, but
we already saw why this was so in last example.

-Doug


More information about the Concurrency-interest mailing list