How can I do "check-then-act" in an AtomicInteger
variable?
I.e. what is the most safe/best way to check the value of such a variable first and inc/dec depending on result?
E.g. (in high level)if(count < VALUE) count++;
//atomically using AtomicInteger
You need to write a loop. Assuming that count
is your AtomicInteger
reference, you would write something like:
while(true)
{
final int oldCount = count.get();
if(oldCount >= VALUE)
break;
if(count.compareAndSet(oldCount, oldCount + 1))
break;
}
The above will loop until either: (1) your if(count < VALUE)
condition is not satisfied; or (2) count
is successfully incremented. The use of compareAndSet
to perform the incrementation lets us guarantee that the value of count
is still oldCount
(and therefore still less than VALUE
) when we set its new value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With