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

Doug Lea dl at cs.oswego.edu
Mon May 15 20:17:39 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?
> 

Plain compareAndSet is always preferred when failure is informative.
A false return from x.compareAndSet(expected, newValue) tells you that the
current value is NOT equal to expected.

For example, suppose you have an AtomicInteger x serving as a lock or semaphore
of some sort. In that case you can write
   if (!x.compareAndSet(0, 1))
     // then lock must already be busy
     // ...



-Doug


More information about the Concurrency-interest mailing list