Java AtomicInteger Class

Category: Java   Tags: Java, Java Thread, Java MultiThread, Thread Synchronization, Immutable Objects

The AtomicInteger class is equivalent to a int variable which can be read and written atomically. It contains atomic operations.

Constructors

AtomicInteger()
Creates a new AtomicInteger with initial value 0.
AtomicInteger(int initialValue)
Creates a new AtomicInteger with given initial value initialValue

Methods

public final int addAndGet(int value)
It will atomically add the given integer value to the current value and returns the updated value.
public final int get()
It will return the current value.
public final void set(int newValue)
It sets to the given new value.
public final int getAndSet(int newValue)
It sets to the newValue and returns the old value.
public final boolean compareAndSet(int expectedValue, int newValue)
It will set the value to the newValue if the current value is equal to expectedValue
public final int getAndIncrement()
It increments current value by one and return the previous value.
public final int getAndDecrement()
It decrements current value by one and return the previous value.
public final int incrementAndGet()
It increments the current value and returns the updated value.
public final int decrementAndGet()
It decrements the current value and returns the updated value.
public final int getAndSet(int newValue)
It sets to the newValue and returns the old value.

Why we need AtomicInteger? In the following Java program two threads are incrementing an int value. If you see the output of this Java program, you will find that count is not incrementing consistently.

WrongCounter.java

                            package com.tutorial.javabasic;

                            class ThreadA implements Runnable {

                                int counter;
                                ThreadA(int count) {
                                    counter = count;
                                }

                                @Override
                                public void run() {
                                    for(int i=1; i<=5; i++) {
                                        counter++;
                                        System.out.println("Count: " + counter);
                                        try {
                                            Thread.sleep(1000);
                                        } catch (InterruptedException ex) {}
                                    }
                                }
                            }

                            class ThreadB implements Runnable {

                                int counter;
                                ThreadB(int count) {
                                    counter = count;
                                }

                                @Override
                                public void run() {
                                    for(int i=1; i<=5; i++) {
                                        counter++;
                                        System.out.println("Count: " + counter);
                                        try {
                                            Thread.sleep(200);
                                        } catch (InterruptedException ex) {}
                                    }
                                }
                            }

                            class WrongCounter {

                                public static void main(String s[]) {
                                    int count = 0;
                                    Thread t1 = new Thread(new ThreadA(count));
                                    Thread t2 = new Thread(new ThreadB(count));
                                    t1.start();
                                    t2.start();
                                }
                            }
                        

Output:

                            Count: 1
                            Count: 1
                            Count: 2
                            Count: 3
                            Count: 4
                            Count: 5
                            Count: 2
                            Count: 3
                            Count: 4
                            Count: 5
                          

To make count consistent we have two choice: use synchronized method or use AtomicInteger. Following program show how to solve the issue using AtomicInteger:

AtomicCounter.java

                            package com.tutorial.javabasic;

                            import java.util.concurrent.atomic.AtomicInteger;

                            class ThreadA implements Runnable {

                                AtomicInteger counter;
                                ThreadA(AtomicInteger count) {
                                    counter = count;
                                }

                                @Override
                                public void run() {
                                    for(int i=1; i<=5; i++) {
                                        System.out.println("Count: " + counter.incrementAndGet());
                                        try {
                                            Thread.sleep(1000);
                                        } catch (InterruptedException ex) {}
                                    }
                                }
                            }

                            class ThreadB implements Runnable {

                                AtomicInteger counter;
                                ThreadB(AtomicInteger count) {
                                    counter = count;
                                }

                                @Override
                                public void run() {
                                    for(int i=1; i<=5; i++) {
                                        System.out.println("Count: " + counter.incrementAndGet());
                                        try {
                                            Thread.sleep(200);
                                        } catch (InterruptedException ex) {}
                                    }
                                }
                            }

                            class AtomicCounter {

                                public static void main(String s[]) {
                                    AtomicInteger count = new AtomicInteger();
                                    Thread t1 = new Thread(new ThreadA(count));
                                    Thread t2 = new Thread(new ThreadB(count));
                                    t1.start();
                                    t2.start();
                                }
                            }
                        

Output:

                            Count: 1
                            Count: 1
                            Count: 2
                            Count: 3
                            Count: 4
                            Count: 5
                            Count: 2
                            Count: 3
                            Count: 4
                            Count: 5