Java Atomic Variable set() vs compareAndSet()

。_饼干妹妹 提交于 2019-12-05 22:55:42

问题


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:

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?


回答1:


The set and compareAndSet methods act differently:

  • 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.

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

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

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



回答2:


As you can see from the open jdk code below.

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

set is just assigning the value and compareAndSet is doing extra operations to ensure atomicity.

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.



来源:https://stackoverflow.com/questions/19238594/java-atomic-variable-set-vs-compareandset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!