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?
compareAndSet. Atomically sets the value to the given updated value if the current value == the expected value.
Atomic is a toolkit of variable java. util. concurrent. atomic package classes, which assist in writing lock and wait-free algorithms with the Java language. An algorithm requiring only partial threads for constant progress is lock-free.
An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer . However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
AtomicInteger class provides operations on underlying int value that can be read and written atomically, and also contains advanced atomic operations. AtomicInteger supports atomic operations on underlying int variable. It have get and set methods that work like reads and writes on volatile variables.
The set
and compareAndSet
methods act differently:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With