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;
}
Author by
Chrisma Andhika
Updated on July 23, 2022Comments
-
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 over 10 yearsThanks 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 over 10 yearsAre you sure that
Atomic
classes are atomic because they use volatile variables to maintain their internal states. If you define a volatile variablevolatile long value
, does an operation likevalue++
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 changevalue
. So having avolatile
variable doesn't guarantee atomicity. An operation/process isatomic
, if they provide support for atomic updates. -
Debojit Saikia over 10 yearsNow, the
set
op is atomic, because it has only one operation:value = newValue;
and is atomic even ifvalue
were not definedvolatile
. Herevalue
was definedvolatile
to use the visibility guarantee that they provide - changes made by one thread is always visible to the other threads.