Java中的Atomic set()和getAndSet()方法之间的区别

问题描述 投票:2回答:1

在我的一个程序中,我试图更新原子整数的值,但无法在set()getAndSet()方法之间做出决定,因为它们似乎都在做同样的事情。我已经通过了thisthis帖子,但是他们正在比较setcompareAndSet(如果线程没有预期值,则放弃设置提供的值)而我有兴趣将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. 什么时候应该使用这些方法?
java multithreading synchronization atomicity atomicinteger
1个回答
1
投票

根据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;
© www.soinside.com 2019 - 2024. All rights reserved.