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

Bill Pugh pugh at cs.umd.edu
Wed May 17 15:39:36 EDT 2006

On May 17, 2006, at 4:43 AM, Doug Lea wrote:

> 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.

I would explain this differently (actually, the JMM requires that it  
be explained differently):

weakCompareAndSet has volatile semantics, _except_ that it doesn't  
create any happens-before

Thus, using weakCompareAndSet is ideal for things such as performance  
unique identifiers and reference counting.

However, what about AtomicReference? If you actually try to pass  
references between threads,
you need to establish a happens-before relationship between the two  
threads, so that the contents of
the object are communicated as well.

So, here is the question we should discuss:


Should weakCompareAndSet on an AtomicReference create happens before  
edges (just as
compareAndSwap does)?


For AtomicInteger, and similar classes, there isn't a question. Just  
for AtomicReference classes.

I talked with Doug, and we agreed that we didn't have enough use  
cases to really decide.

The only possible use for a weakCompareAndSet on a reference where  
you don't need a happens-before
edge is if you can prove that a happens-before edge is created by  
some other mechanism.

So, if weakCompareAndSet does not establish a happens-before  
ordering, then a few people (i.e, just Doug)
might be able to effectively use it to superoptimize some code.  
However, without the happens-before ordering,
some potential use cases are invalid, and many people trying to use  
it will create a data race.



More information about the Concurrency-interest mailing list