在我的一个程序中,我试图更新原子整数的值,但无法在set()
和getAndSet()
方法之间做出决定,因为它们似乎都在做同样的事情。我已经通过了this和this帖子,但是他们正在比较set
和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()
返回的值。根据java documentation,他们都做了不同的事情:
AtomicReference#getAndSet
会将内部值设置为您传入的内容,但会返回旧值。
AtomicReference<Integer> reference = new AtomicReference<>(10);
int value = reference.getAndSet(14);
System.out.println(value); // prints 10
AtomicReference#set
将设置内部值,就是这样。它返回void。
AtomicReference<Integer> reference = new AtomicReference<>(10);
reference.set(15);
System.out.println(reference.get()); // prints 15;