Jim
Jim

Reputation: 19552

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

Upvotes: 4

Views: 2193

Answers (2)

You can solve it like this if you're using Java 8. It's thread safe and is being performed atomically.

AtomicInteger counter = new AtomicInteger();
static final int COUNT = 10;

public int incrementUntilLimitReached() {
    return counter.getAndUpdate((n -> (n < COUNT) ? n + 1 : n));
}

Upvotes: 1

ruakh
ruakh

Reputation: 183241

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.

Upvotes: 10

Related Questions