As in the other examples we’re going to implement a counter, shared by many workers, that will allow to decrease a number until zero is reached. The problem is that it has to do two operations:

Make sure to not decrease below 0.

Decrease the number by 1.

Solution:

In previous posts we were using synchronized keyword to make sure that only one worker is executing Counter.dec() method. Here we’re going to use AtomicInteger form java.util.concurrent.atomic package and its updateAndGet(IntUnaryOperator updateFunction) method that will update the current value with result of applying updateFunction and return the new value: