(请注意,此问题不是关于CAS的,而是关于“可能偶然失败”的Javadoc)。
这两个方法与AtomicInteger类的两种方法之间的Javadoc唯一区别是,weakCompareAndSet包含以下注释:“可能会虚假失败”。
现在,除非我的眼睛因某种咒语而被欺骗,否则这两种方法的确看起来完全一样:
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);
}
因此,我意识到“ May”并不意味着“ Must”,但是为什么我们不都开始将其添加到我们的代码库中:
public void doIt() {
a();
}
/**
* May fail spuriously
*/
public void weakDoIt() {
a();
}
我对那个看上去与compareAndSet()一样的弱CompareAndSet()感到困惑,但是“可能会虚假地失败”,而另一个却不能。
显然,“弱”和“虚假失败”与“先发生”排序有关,但是我对这两种AtomicInteger(和AtomicLong等)方法仍然感到困惑:因为显然它们调用的是完全相同的不安全方法 .compareAndSwapInt方法。
我对Java 1.5引入AtomicInteger感到特别困惑,因此在Java内存模型更改后(显然,它不能“在1.4中错误地失败”,但是其行为更改为“在1.5中不可错误地失败”) 。