Given an AtomicLong
object, what is the right way to decrement the value by a delta?
Option 1
AtomicLong count = new AtomicLong(0L);
public void decrementCount(long decrementBy) {
count.getAndUpdate(l->count.get() - decrementBy);
}
Option 2
AtomicLong count = new AtomicLong(0L);
public void decrementCount(long decrementBy) {
count.getAndAdd(-decrementBy);
}
While both give the desired result, I want to understand under what circumstance will they not represent the desired behavior i.e to decrement a long value atomically? (One drawback of the second approach for example could be the negative sign causing some bit overflow but I am not sure if that's true)
CodePudding user response:
It seems that you are looking for getAndAdd
), which:
Atomically adds the given value to the current value
AtomicLong count = new AtomicLong(0L);
count.getAndAdd(-decrementBy);
CodePudding user response:
count.getAndUpdate(l->count.get() - decrementBy);
This doesn't work atomically.
You're re-reading count.get()
inside the lambda; when you do that, it might be changed by some other thread prior to this update being applied.
You already have the current value, in l
:
count.getAndUpdate(l->l - decrementBy);
But getAndAdd(-decrementBy)
is easier.
CodePudding user response:
I think that this class, has all methods prepared to:
The AtomicLong class provides you with a long variable which can be read and written atomically, and which also contains advanced atomic operations
is depending on the order that you want use before and after that update or update first and read after. You have arpopiate methods for incrementing and decrementing:
addAndGet()
getAndAdd()
getAndIncrement()
incrementAndGet()
getAndDecrement()
decrementAndGet()
then something like this:
AtomicLong atomicLong = new AtomicLong(22);
System.out.println(atomicLong.getAndAdd(-1));
System.out.println(atomicLong.addAndGet(-1));
hope this helps