[英]What is the difference between compareAndExchange vs compareAndExchangeAcquire
这是来自 Java 库的片段:
public final boolean compareAndExchangeAcquire(boolean expectedValue, boolean newValue) {
return (int)VALUE.compareAndExchangeAcquire(this,
(expectedValue ? 1 : 0),
(newValue ? 1 : 0)) != 0;
}
它来自AtomicBoolean
class。 转换为int
如何返回boolean
?
我的主要问题: compareAndExchange
与compareAndExchangeAcquire
有什么区别?
通俗地说:在xxxRelease
之前和xxxAcquire
之后编写的语句可以在应用xxx
时自由地重新排序。
您发布的代码的最后一部分是!= 0
。 带有澄清变量:
int a = (int)VALUE.compareAndExchangeAcquire(this,
(expectedValue ? 1 : 0),
(newValue ? 1 : 0));
return a != 0;
当然!=
运算符返回 boolean。
至于问题的第二部分:
另外, compareAndExchange 与 compareAndExchangeAcquire 有什么区别?
首先一些必读: https://stackoverflow.com/a/16181675/3424746
从上面的答案中,您应该了解编译器/处理器可以重新排序加载/存储,以及获取和释放的限制。 比较和交换最有可能使用 CAS 指令来实现,可以将其视为加载+存储。 compareAndExchangeAcquire
和compareAndExchangeRelease
将释放/获取语义添加到有问题的 CAS/加载+存储。 换句话说,您可以使用这些来防止某些重新排序,或允许某些重新排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.