[concurrency-interest] propper way to use CAS ?

Brian Goetz brian at quiotix.com
Sun Oct 9 11:18:09 EDT 2005


> in many concurrent classes when compare-and-set (cas) is used- it is an 
> endless loop of competing threads trying to fight over an object (,say, 
> a queue's tail in order to connect a new element (reference)) .
> 
> Wouldn't it be benefitial to perform a thread.Yield() after N 
> (pre-configured) unsuccessful CAS retries ? wouldnt it give better 
> overall performance ?

It depends on the degree of contention you expect to experience.

In most cases, the standard approach (retry continuously) is best.  Only 
when you are expecting very heavy contention, where you expect most CAS 
attempts to fail, is a more sophisticated backoff strategy beneficial.

When there is no contention for a CAS, it always succeeds.  When 
multiple threads compete for a CAS, one will always win and make 
progress.  So the question is, what percent of CAS attempts will lose 
and need to be retried?  Only if this ratio is high will a better 
contention management strategy be a win.  This is a function of how many 
threads are involved, and the ratio of CAS to "other work".

If your contention is so high that most CAS attempts fail, you might be 
better off with a lock, as locking automatically addresses the problem 
you raise fairly well, by blocking so as not to create more contention.



More information about the Concurrency-interest mailing list