Skip to main content

java.util.concurrent.atomic AtomicLong weakCompareAndSet VS compareAndSet

No replies
Joined: 2007-12-01
Points: 0


I'm trying to create class which collects performance statistics.
I would like make this class as fast as possible for obvious reasons.
So I would like to use AtomicLong class to keep performance factors. Even more, I would like to use weak* operations because I don't need happens-before relationships here. I just need see changes to performance factor and nothing else (even javadoc advice use of weak* methods in this context).

I have one question and two thought.
1) Question about weakCompareAndSet
In javadoc there is information that this method may 'fail spuriously'. In javadoc for java.util.concurrent.atomic package there is sentence:
"On some platforms, the weak version may be more efficient than compareAndSet in the normal case, but differs in that any given invocation of the weakCompareAndSet method may return false spuriously (that is, for no apparent reason)."
My question is: Does "method may fail spuriously" means exactly the same as "method may return false" ? I mean, when this method return false, does it _always_ means that value has not be unchanged? so then I can use following construction to implement weakIncrement() (I just modified getAndIncrement):
AtomicLong counter = new AtomicLong();
while (true) {
long current = counter.get();
long next = current + 1;
if (counter.weakCompareAndSet(current, next))
and I can be sure that one invocation of weakIncrement() always increments counter by one.

2) more weak* methods.
When you take a look into i.e. AtomicLong sources, you can see that above patter in commonly use to implement AtomicLong's methods.
Maybe it would be good to introduce more weak* methods (like weakAdd())? I think that in context of performance factor there is no need to happen-before relationships between threads which modify such factor.

3) compareAndSet == weakCompareAndSet ?
I have just copied this to from JDK 1.6.0_12's sources:
public final boolean compareAndSet(long expect, long update) {
return unsafe.compareAndSwapLong(this, valueOffset, expect, update);

public final boolean weakCompareAndSet(long expect, long update) {
return unsafe.compareAndSwapLong(this, valueOffset, expect, update);
Maybe I'm blind but where is the difference? ;)
Is there any JVM/platform which actually utilize freedom of weakCompareAndSet?