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

Doug Lea dl at cs.oswego.edu
Mon May 15 07:41:12 EDT 2006


Hanson Char wrote:
> 
> Does the following code look good to you ?  Is it a good case or 
> "proper" use of weakCompareAndSet ? 


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.

> 
> public class Foo {
>     private volatile int latency = -1;
>     private final AtomicInteger maxLatency = new AtomicInteger(-1);
> 
>     public void setLatency(int latency)
>     {
>         this.latency = latency;
>         updateMaxLatency(latency);
>     }
> 
>     private void updateMaxLatency(int latency)
>     {
>         for (;;) {
>             int maxLatencySnapshot = this.maxLatency.get();
>            
>             if (latency > maxLatencySnapshot)
>             {
>                 if (this.maxLatency.weakCompareAndSet 
> (maxLatencySnapshot, latency))
>                     return; // new max succesfully set
>                 // race condition or just fail spuriously; so let's retry
>                 continue;
>             }
>             return;
>         }
>     }
> }
> 
> 


-Doug



More information about the Concurrency-interest mailing list