简体   繁体   中英

What is the difference between compareAndExchange vs compareAndExchangeAcquire

Here is a snippet from Java library:

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. How can a cast to int return a boolean ?

My main question: What is the difference between compareAndExchange vs compareAndExchangeAcquire ?


In layman terms: statements written prior to xxxAcquire and after xxxRelease is free to reorder while applying xxx .

在此处输入图像描述

The last part of the code you posted is != 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.

As for the second part of the question:

Also, what is the difference between compareAndExchange vs compareAndExchangeAcquire?

Firstly some required reading: 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. compareAndExchangeAcquire and compareAndExchangeRelease add the release/acquire semantics to the CAS/load+stores in question. In other words you can use these to prevent certain reorderings, or allow certain reorderings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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