Search code examples
javaconcurrencyjava-14

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.

enter image description here


Solution

  • 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.