Java Atomic Variable set () vs compareAndSet ()

I want to know the difference between set () and compareAndSet () in atomic classes. Does the set () method support 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 these two methods the same?

+6
source share
2 answers

The set and compareAndSet act differently:

  • compareAndSet: Atomically sets the value for this updated value if the current value is (==) the expected value.
  • set: Set to the given value.

Does the set () method support the atomic process?

Yes. It is atomic. Because for set , only one operation is used for the new value. The following is the source code for the set method:

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

As you can see from the open source jdk 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 simply assigns a value, and compareAndSet performs additional 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

For the design of any atomic operations, it is necessary to consider the return value (logical).

-1
source

Source: https://habr.com/ru/post/955461/


All Articles