Java Atomic Variable set() vs compareAndSet()

Chrisma Andhika picture Chrisma Andhika · Oct 8, 2013 · Viewed 10.6k times · Source

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?

Answer

Debojit Saikia picture Debojit Saikia · Oct 8, 2013

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;
}