[concurrency-interest] AtomicReference weakCompareAndSet "May fail spuriously"?

Doug Lea dl at cs.oswego.edu
Thu Feb 2 06:59:05 EST 2006

Robert Kuhar wrote:
> I was strolling through the Docs one day, and came upon the JDK 1.5 Javadocs
> for Class java.util.concurrent.atomic.AtomicReference.  The description for the
> weakCompareAndSet method confuses me:
>   public final boolean weakCompareAndSet(V expect, V update)
>   Atomically set the value to the given updated value if the current 
>   value == the expected value. May fail spuriously.
>   Parameters:
>     expect - the expected value
>     update - the new value 
>   Returns:
>     true if successful.
> What does "May fail spuriously" mean?  Why would it fail spuriously?  When the
> spurious failures occur, is the return value always false?  Why would anyone
> call this method having been warned that "spurious failure" is possible?  I
> think I'm missing something here.


The javadocs in the atomic package also mention that this form may be more
efficient. (At least on some processors; on most (in fact all supported by
hotspot) it actually compiles to the same code.) The reason that it may be more
efficient is that some processors perform CAS via a pair of Load-linked /
Store-conditional instructions, which may fail if some other processor
happened to write to the same cache line, among other reasons that have
nothing to do with the CAS. In some cases, this is acceptable. On
such processors, a full strong CAS must actually be coded internally
as a loop. There are a handfull of non-blocking algorithms out there
where you don't actually want that loop, so we include this method
so you can avoid it. We expect use of this method to be uncommon.


More information about the Concurrency-interest mailing list