6

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.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
T-Bag
  • 10,916
  • 3
  • 54
  • 118

1 Answers1

11

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

i.e. 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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 2
    But they both are using different memory instructions - that is COMPARE_AND_EXCHANGE and COMPARE_AND_SET will that make any difference in the reslut – T-Bag Mar 12 '20 at 06:30
  • 1
    @Eran Why would `compareAndExchange​(1,2)` return 1 if the previous value was 1. Shouldn't it return the *current value* which would be 2? –  Oct 07 '20 at 18:38
  • 1
    based on the following discussion, CAS could be faster than CAE: https://bugs.openjdk.java.net/browse/JDK-8141640 – AlexO Feb 07 '21 at 14:40