在我的一个程序中,我试图更新 Atomic Integer 的值,但无法在set()
和getAndSet()
方法之间做出决定,因为它们似乎都做同样的事情。我已经阅读了这篇文章和这篇文章,但是他们正在比较set
and compareAndSet
(如果线程没有预期值,则放弃设置提供的值)而我有兴趣比较set
(setAndGet
仅在设置提供的值后返回值)。
//Sets the newValue to the volatile member value
public final void set(int newValue) {
value = newValue;
}
和
public final int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}
//Doesn't give up until it sets the updated value. So eventually overwrites the latest value.
public final int getAndSetInt(Object paramObject, long paramLong, int paramInt) {
int i;
do {
i = getIntVolatile(paramObject, paramLong);
} while (!compareAndSwapInt(paramObject, paramLong, i, paramInt));
return i;
}
我无法找出这两种方法之间的任何主要区别。
set()
我们有的时候为什么有getAndSet()
。可以选择不使用返回的值getAndSet()
。什么时候应该使用这些方法?