Java 原子变量 set() 与 compareAndSet()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19238594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:20:37  来源:igfitidea点击:

Java Atomic Variable set() vs compareAndSet()

javasetatomiccompare-and-swap

提问by Chrisma Andhika

I want to know the difference between set() and compareAndSet() in atomic classes. Does the set() method also ensure the atomic process? For example this code:

我想知道原子类中 set() 和 compareAndSet() 之间的区别。set() 方法是否也确保了原子过程?例如这段代码:

public class sampleAtomic{
    private static AtomicLong id = new AtomicLong(0);

    public void setWithSet(long newValue){
        id.set(newValue);
    }

    public void setWithCompareAndSet(long newValue){
        long oldVal;
        do{
            oldVal = id.get();
        }
        while(!id.compareAndGet(oldVal,newValue)
    }
}

Are the two methods identical?

两种方法一样吗?

采纳答案by Debojit Saikia

The setand compareAndSetmethods act differently:

setcompareAndSet方法采取不同的:

  • compareAndSet : Atomically sets the value to the given updated value if the current value is equal (==) to the expected value.
  • set : Sets to the given value.
  • compareAndSet :如果当前值等于 (==) 预期值,则原子地将值设置为给定的更新值。
  • set :设置为给定值。

Does the set() method also ensure the atomic process?

set() 方法是否也确保了原子过程?

Yes. It is atomic. Because there is only one operation involved to setthe new value. Below is the source code of the setmethod:

是的。它是原子的。因为set新值只涉及一个操作。下面是该set方法的源代码:

public final void set(long newValue) {
        value = newValue;
}

回答by Gireesh

As you can see from the open jdk code below.

正如您从下面打开的 jdk 代码中看到的那样。

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/atomic/AtomicLong.java#AtomicLong.set%28long%29

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/atomic/AtomicLong.java#AtomicLong.set%28long%29

setis just assigning the value and compareAndSetis doing extra operations to ensure atomicity.

set只是分配值并且compareAndSet正在执行额外的操作以确保原子性。

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/atomic/AtomicLong.java#AtomicLong.compareAndSet%28long%2Clong%29

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/atomic/AtomicLong.java#AtomicLong.compareAndSet%28long%2Clong%29

The return value (boolean) needs to be considered for designing any atomic operations.

设计任何原子操作时都需要考虑返回值(布尔值)。