In one of my programs, I was trying to update the value of an Atomic Integer, but could not decide between set()
and getAndSet()
methods because they both seem to do the same. I have already gone through this and this post, but they are comparing set
and compareAndSet
(which gives up setting the provided value, if the thread doesn't have the expected value) whereas I am interested to compare set
with setAndGet
(which returns only after setting the provided value).
//Sets the newValue to the volatile member value
public final void set(int newValue) {
value = newValue;
}
and
public final int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}
//Doesn't give up until it sets the updated value. So eventually overwrites the latest value.
public final int getAndSetInt(Object paramObject, long paramLong, int paramInt) {
int i;
do {
i = getIntVolatile(paramObject, paramLong);
} while (!compareAndSwapInt(paramObject, paramLong, i, paramInt));
return i;
}
I am not able to find out any major difference between the two methods.
Why have
set()
when we havegetAndSet()
. One may choose to not use the value returned bygetAndSet()
.When should one use each of these methods?