The source code is the same thing.
public final boolean compareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}
public final boolean weakCompareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}
What's the point?
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.
AtomicReference class provides operations on underlying object reference that can be read and written atomically, and also contains advanced atomic operations. AtomicReference supports atomic operations on underlying object reference variable.
On x86 the LOCK CMPXCHG instruction is used to implement CAS. It is atomic, provides (near-)maximal ordering guarantees and does not suffer from spurious failures. So on x86 platforms there is nothing to gain from a CAS with fewer guarantees.
But on other platforms such as PowerPC or ARM (without LSE extension) CAS is implemented as a sequence of several instructions which provide LL/SC behavior and memory barriers as separate building blocks. This creates some wiggle room how strong your CAS can be both in terms of ordering and failure guarantees. Conversely it means a full-strength CAS can be more costly instruction sequence than required by some concurrent algorithms.
Many concurrent algorithms involve loops that retry or recompute an operation when a CAS fails and then try again. Since LL/SC can fail spuriously a strong CAS implementation based on it has to loop internally. If the code already contains an outer loop it can avoid the inner loop by replacing the strong CAS with a weak CAS that is allowed to fail spuriously.
So weakCAS exists to allow more efficient code on weakly ordered architectures.
The javadoc is vague about what exactly the weakened ordering means because it currently cannot be expressed in terms of the java memory model. That may be revised in the future when it will be more closely aligned with the C++11 memory model.
The table in the Multiprocessor chapter of the JSR-133 Cookbook provides an overview how platforms differ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With