4

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

Jim
  • 18,826
  • 34
  • 135
  • 254
  • 1
    http://stackoverflow.com/questions/4818699/practical-uses-for-atomicinteger – user219882 Mar 30 '12 at 11:26
  • @Tomas:I don't see an answer to this at your link.Only how to use it.How can I do a check-then-act atomically? – Jim Mar 30 '12 at 11:31

2 Answers2

10

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.

ruakh
  • 175,680
  • 26
  • 273
  • 307
1

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));
}