Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can weakCompareAndSet fail spuriously if it is implemented exactly like compareAndSet?

(note that this question is not about CAS, it's about the "May fail spuriously" Javadoc).

The only difference in the Javadoc between these two methods from the AtomicInteger class is that the weakCompareAndSet contains the comment: "May fail spuriously".

Now unless my eyes are cheated by some spell, both method do look to be doing exactly the same:

public final boolean compareAndSet(int expect, int update) {   return unsafe.compareAndSwapInt(this, valueOffset, expect, update); }  /* ...  * May fail spuriously.  */ public final boolean weakCompareAndSet(int expect, int update) {   return unsafe.compareAndSwapInt(this, valueOffset, expect, update); } 

So I realize that "May" doesn't mean "Must" but then why don't we all start adding this to our codebase:

public void doIt() {     a(); }  /**  * May fail spuriously  */ public void weakDoIt() {     a(); } 

I'm really confused with that weakCompareAndSet() that appears to do the same as the compareAndSet() yet that "may fail spuriously" while the other can't.

Apparently the "weak" and the "spurious fail" are in a way related to "happens-before" ordering but I'm still very confused by these two AtomicInteger (and AtomicLong etc.) methods: because apparently they call exactly the same unsafe.compareAndSwapInt method.

I'm particularly confused in that AtomicInteger got introduced in Java 1.5, so after the Java Memory Model change (so it is obviously not something that could "fail spuriously in 1.4" but whose behavior changed to "shall not fail spuriously in 1.5").

like image 906
SyntaxT3rr0r Avatar asked Mar 14 '10 18:03

SyntaxT3rr0r


People also ask

What is spurious failure?

failure triggering an action in an untimely manner.

What is weakCompareAndSet?

The weakCompareAndSet javadoc explains it thus: Atomically sets the value to the given updated value if the current value == the expected value. May fail spuriously and does not provide ordering guarantees, so is only rarely an appropriate alternative to compareAndSet.


1 Answers

There is a difference between implementation and specification...

Whilst on a particular implementation there may not be much point in providing different implementations, future implementations perhaps on different hardware may want to. Whether this method carries its weight in the API is debatable.

Also the weak methods do not have happens-before ordering defined. The non-weak versions behave like volatile fields.

like image 139
Tom Hawtin - tackline Avatar answered Sep 21 '22 06:09

Tom Hawtin - tackline