简体   繁体   English

compareAndExchange 与 compareAndExchangeAcquire 有什么区别

[英]What is the difference between compareAndExchange vs compareAndExchangeAcquire

Here is a snippet from Java library:这是来自 Java 库的片段:

public final boolean compareAndExchangeAcquire(boolean expectedValue, boolean newValue) {
    return (int)VALUE.compareAndExchangeAcquire(this,
                                                (expectedValue ? 1 : 0),
                                                (newValue ? 1 : 0)) != 0;
}

It is from AtomicBoolean class.它来自AtomicBoolean class。 How can a cast to int return a boolean ?转换为int如何返回boolean

My main question: What is the difference between compareAndExchange vs compareAndExchangeAcquire ?我的主要问题: compareAndExchangecompareAndExchangeAcquire有什么区别?


In layman terms: statements written prior to xxxAcquire and after xxxRelease is free to reorder while applying xxx .通俗地说:在xxxRelease之前和xxxAcquire之后编写的语句可以在应用xxx时自由地重新排序。

在此处输入图像描述

The last part of the code you posted is != 0 .您发布的代码的最后一部分是!= 0 With clarifying variable:带有澄清变量:

int a = (int)VALUE.compareAndExchangeAcquire(this,
                                                (expectedValue ? 1 : 0),
                                                (newValue ? 1 : 0));
return a != 0;

Of course the != operator returns a boolean.当然!=运算符返回 boolean。

As for the second part of the question:至于问题的第二部分:

Also, what is the difference between compareAndExchange vs compareAndExchangeAcquire?另外, compareAndExchange 与 compareAndExchangeAcquire 有什么区别?

Firstly some required reading: https://stackoverflow.com/a/16181675/3424746首先一些必读: https://stackoverflow.com/a/16181675/3424746

From the above answer you should understand that compilers/processors can reorder loads/stores, and the restrictions that acquires and releases place on those.从上面的答案中,您应该了解编译器/处理器可以重新排序加载/存储,以及获取和释放的限制。 Compare and exchange is most likely implemented with a CAS instruction, which can be viewed as a load+store.比较和交换最有可能使用 CAS 指令来实现,可以将其视为加载+存储。 compareAndExchangeAcquire and compareAndExchangeRelease add the release/acquire semantics to the CAS/load+stores in question. compareAndExchangeAcquirecompareAndExchangeRelease将释放/获取语义添加到有问题的 CAS/加载+存储。 In other words you can use these to prevent certain reorderings, or allow certain reorderings.换句话说,您可以使用这些来防止某些重新排序,或允许某些重新排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM