Google
 
Web unafbapune.blogspot.com

Monday, May 15, 2006

 

j.u.c.atomic.Atomic*.weakCompareAndSet

I have been wondering what it means when it "fails spuriously" in invoking those weakCompareAndSet methods in Java 5, and what a good use case would be like. It turns out the spurious "failure" simply means the method would do nothing and return false for no apparent reason.

Sample Usage:
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))
// race condition or just fail spuriously; so let's retry
continue;
}
return;
}
}
// ...
}
As commented by Doug Lea:
"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."
Special thanks to David Holmes for his generous and thorough explanation.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?