Java 的AtomicInteger优惠public final boolean compareAndSet(int expect, int update)。如果false返回,我想知道比较失败时的实际值是多少。这在Java中可能吗?
在 .Net 中,有public static int CompareExchange(ref int location1, int value, int comparand),它总是返回原始值。
Java 的AtomicInteger优惠public final boolean compareAndSet(int expect, int update)。如果false返回,我想知道比较失败时的实际值是多少。这在Java中可能吗?
在 .Net 中,有public static int CompareExchange(ref int location1, int value, int comparand),它总是返回原始值。
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;
}
}
}
(这种循环是大多数操作AtomicInteger的实现方式:get循环,执行一些逻辑,尝试比较和设置。)
API 没有公开这样的方法。更重要的是,Oracle 实现用于sun.misc.Unsafe执行本机 CAS 操作,并且该类型也不公开它。
get()一种选择是如果compareAndSet返回就调用false。但是,当您检查它时,实际值AtomicInteger可能已经改变。你无能为力。对于Interlocked方法也是如此。你必须澄清你想用这个值做什么才能走得更远。