Java Atomic Variable set() vs compareAndSet()

10,914

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;
}
Share:
10,914
Chrisma Andhika
Author by

Chrisma Andhika

Updated on July 23, 2022

Comments

  • Chrisma Andhika
    Chrisma Andhika almost 2 years

    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?

  • Chrisma Andhika
    Chrisma Andhika over 10 years
    Thanks for your answer. I forgot to check the source code. You are right to say that set method is atomic, but the reason is not because it is only has one operation. Automatic classes has member variable called value and that variable is volatile (the one in the set method body above), so the set method should be thread-safe.
  • Debojit Saikia
    Debojit Saikia over 10 years
    Are you sure that Atomic classes are atomic because they use volatile variables to maintain their internal states. If you define a volatile variable volatile long value, does an operation like value++ is atomic? And the answer is no. This operation is not atomic; it is actually three distinct operations-fetch the value, add one to it, write the updated value back. In the mean time, another thread can change value. So having a volatile variable doesn't guarantee atomicity. An operation/process is atomic, if they provide support for atomic updates.
  • Debojit Saikia
    Debojit Saikia over 10 years
    Now, the set op is atomic, because it has only one operation: value = newValue; and is atomic even if value were not defined volatile. Here value was defined volatile to use the visibility guarantee that they provide - changes made by one thread is always visible to the other threads.