AtomicInteger.compareAndSet 返回原始值,而不是布尔值

Eug*_*sky 5 java atomic compare-and-swap atomicinteger

Java 的AtomicInteger优惠public final boolean compareAndSet(int expect, int update)。如果false返回,我想知道比较失败时的实际值是多少。这在Java中可能吗?

在 .Net 中,有public static int CompareExchange(ref int location1, int value, int comparand), 总是返回原始值。

Lou*_*man 2

public int getAndCompareAndSet(AtomicInteger ai, int expected, int update) {
  while (true) {
    int old = ai.get();
    if (old != expected) {
      return old;
    } else if (ai.compareAndSet(old, update)) {
      return old;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

(这种循环是大多数操作的AtomicInteger实现方式:get 循环、执行一些逻辑、尝试比较和设置。)