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?