以下是AtomicStamedReference中compareAndSet方法的源码
public boolean compareAndSet(V expectedReference,
V newReference,
int expectedStamp,
int newStamp) {
Pair<V> current = pair;
return
expectedReference == current.reference &&
expectedStamp == current.stamp &&
((newReference == current.reference &&
newStamp == current.stamp) ||
casPair(current, Pair.of(newReference, newStamp)));
}
从上述源码可知reference与stamp比较时使用的是==而非equal方法。
因此expectedReference因直接传入getReference()方法的返回值。同时对原始数据类型的使用需特别注意。以下为错误示例:
❌
public class AtomicStampedTest {
private static AtomicStampedReference<Integer> atomicInteger = new AtomicStampedReference<>(0, 0);
public static Integer incrAtomicInteger(AtomicStampedReference<Integer> atomicInteger){
while (true) {
final int timeStamp = atomicInteger.getStamp();
int /* ❌错误,应改为Integer*/ currunt = atomicInteger.getReference();
Integer attemptValue = currunt + 1;
int nextStamp = timeStamp + 1;
if (atomicInteger.compareAndSet(currunt, attemptValue, timeStamp, nextStamp)) {
return attemptValue;
}
}
}
public static void main(String[] args) {
Integer value = incrAtomicInteger(atomicInteger);
System.out.println(value);
}
}