3

在我的一个程序中,我试图更新 Atomic Integer 的值,但无法在set()getAndSet()方法之间做出决定,因为它们似乎都做同样的事情。我已经阅读了这篇文章和这篇文章,但是他们正在比较setand compareAndSet(如果线程没有预期值,则放弃设置提供的值)而我有兴趣比较setsetAndGet在设置提供的值后返回值)。

   //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;
}

我无法找出这两种方法之间的任何主要区别。

  1. set()我们有的时候为什么有getAndSet()。可以选择不使用返回的值getAndSet()

  2. 什么时候应该使用这些方法?

4

1 回答 1

1

根据java 文档,它们都做不同的事情:

AtomicReference#getAndSet会将内部值设置为您传入的任何值,但会返回旧值。

AtomicReference<Integer> reference = new AtomicReference<>(10);
int value = reference.getAndSet(14);
System.out.println(value); // prints 10

AtomicReference#set将设置内部值,仅此而已。它返回无效。

AtomicReference<Integer> reference = new AtomicReference<>(10);
reference.set(15);
System.out.println(reference.get()); // prints 15;
于 2019-04-24T13:16:14.980 回答