Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AtomicInteger safely to check first

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

like image 660
Jim Avatar asked Dec 21 '22 00:12

Jim


1 Answers

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.

like image 134
ruakh Avatar answered Jan 04 '23 05:01

ruakh