Search code examples
javaconcurrentmodificationatomicinteger

How to update an Atomic based on a condition?


How to update an AtomicInteger if its current value is less than the given value? The idea is:

AtomicInteger ai = new AtomicInteger(0);
...
ai.update(threadInt); // this call happens concurrently
...
// inside AtomicInteger atomic operation
synchronized {
    if (ai.currentvalue < threadInt)
        ai.currentvalue = threadInt;
}

Solution

  • If you are using Java 8 you can use one of the new update methods in AtomicInteger, which you can pass a lambda expression. For example:

    AtomicInteger ai = new AtomicInteger(0);
    
    int threadInt = ...
    
    // Update ai atomically, but only if the current value is less than threadInt
    ai.updateAndGet(value -> value < threadInt ? threadInt : value);