简体   繁体   中英

compareandexchange() vs compareandset() of Atomic-Integer

While working on AtomicInteger, I found this API provides two Methods.

compareAndExchange :

Atomically sets the value to newValue if the current value, referred to as the witness value, == expectedValue, with memory effects as specified by VarHandle.compareAndExchange(java.lang.Object...)

compareAndSet :

Atomically sets the value to newValue if the current value == expectedValue , with memory effects as specified by VarHandle.compareAndSet(java.lang.Object...) .

I am unable to understand difference between two, Please help with suitable example.

The two methods have a different return type.

compareAndSet returns boolean :

true if successful. False return indicates that the actual value was not equal to the expected value.

compareAndExchange returns an int :

the witness value, which will be the same as the expected value if successful

ie compareAndSet indicates whether the value of the variable was updated, while compareAndExchange returns the current value of the variable, which gives you more information.

compareAndSet(1,2) will set the value of the atomic integer to 2 if the previous value was 1 , and will return true in that case. Otherwise, it will not set the value, and it will return false .

compareAndExchange​(1,2) will set the value of the atomic integer to 2 if the previous value was 1 , and will return 1 in that case. If the previous value wasn't 1 , it will not set the value, and will return the current (unchanged) value.

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