AtomicInteger: keep non-negative

Is there a way to perform the “decrease if the result is positive or zero” using AtomicInteger ? To clarify the desired behavior:

  • if the current value is greater than zero, decrement
  • if the current value is zero do nothing
  • (negative current value is not processed)
+7
java concurrency atomicity
source share
2 answers

In Java 8, yes :

 atomicInteger.updateAndGet(i -> i > 0 ? i - 1 : i); 

Before Java 8, no .

+10
source share

I suppose you could do something like this pre-Java 8:

 int val = atomicInt.get(); boolean success = false; while(val > 0 && !success) { success = atomicInt.compareAndSet(val, val - 1); if(!success) { // Try again if the value is still > 0 val = atomicInt.get(); } } // Check 'success' to see if it worked 

Not the most elegant code, but I think it does the trick.

+3
source share

All Articles