Java Programming Tutorials

Java programming tutorials with many code examples!

Java Atomic Example


How to use Java Atomic classes to implement lock-free thread-safe code? In this post we’re going to show AtomicInteger mixed with Java 8 functions. Read on!

In a couple of previous posts (Java synchronized method, Java synchronized object, and Java volatile and atomic operations) we’ve shown how to synchronize data access to make code thread-safe. In this post we’re going to show how to use atomic classes that shipped with Java 5 to implement lock-free, thread-safe code.

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:

  1. Make sure to not decrease below 0.
  2. Decrease the number by 1.


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:


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicExample {

    private static class Counter {

        private final AtomicInteger number;

        public Counter(int number) {
            this.number = new AtomicInteger(number);

         * @return true if still can decrease
        public boolean dec() {
            // updateAndGet(fn) executed atomically:
            return number.updateAndGet(n -> (n > 0) ? n - 1 : n) > 0;

    private static class Worker implements Runnable {

        private static int nth = 0;

        private final int id = ++nth;
        private Counter counter;

        public Worker(Counter counter) {
            this.counter = counter;

        public void run() {
            System.out.println("Starting worker: " + id);
            while (counter.dec()) {
                System.out.printf("Worker %2d saw value: %2d%n",
                        id, counter.number.intValue());

    public static void main(String[] args) {
        Counter counter = new Counter(10);
        ExecutorService executor = Executors.newCachedThreadPool();
        for (int i = 1; i <= 10; ++i) {
            executor.execute(new Worker(counter));

        System.out.println("Number actually is: " + counter.number);

AtomicInteger (and other atomic classes) has been extended in Java 8 with the following two methods (among others):

  • int getAndUpdate(IntUnaryOperator updateFunction)
  • int updateAndGet(IntUnaryOperator updateFunction)

Both methods allow to easily pass update functions. The update function have to be side-effects free, because may be called a couple of times.

And here is the result of executing the above example:

Starting worker: 2
Starting worker: 1
Starting worker: 3
Starting worker: 4
Starting worker: 5
Starting worker: 6
Starting worker: 7
Starting worker: 8
Starting worker: 9
Starting worker: 10
Worker  4 saw value:  8
Worker  5 saw value:  1
Worker  8 saw value:  2
Worker  2 saw value:  2
Worker  9 saw value:  4
Worker  1 saw value:  5
Worker 10 saw value:  6
Worker  6 saw value:  7
Worker  7 saw value:  8
Number actually is: 0

Nice! :-)

Was it helpful? Share!