AtomicInteger in java - Detailed explanation with full program




In this thread concurrency tutorial we will learn what is AtomicInteger in java with program and examples. We will learn important methods of AtomicInteger like getAndSet, compareAndSet, incrementAndGet, getAndAdd, getAndIncrement, decrementAndGet, getAndDecrement and how to use them in thread concurrency in java.

Contents of page :
  • 1) What is AtomicInteger in java ?
  • 1.1) AtomicInteger constructors >
  • AtomicInteger()
  • AtomicInteger(int initialValue)
  • 1.2) AtomicInteger important Methods in java >
  • int get()
  • void set(int newValue)
  • int getAndSet(int newValue)
  • boolean compareAndSet(int expect, int update)
  • 1.3) Addition methods of AtomicInteger  >
  • int addAndGet(int value)
  • int incrementAndGet()
  • int getAndAdd(int value)
  • int getAndIncrement()
  • 1.4) Subtraction methods of AtomicInteger >
  • int decrementAndGet()
  • int getAndDecrement()

  • 2) Example/Program to demonstrate usage of AtomicInteger in java >
  • 2.1) Occasionally output may be different >

  • 3) Program to show Consequences of using Integer in place of AtomicInteger in java >


1) What is java.util.concurrent.atomic.AtomicInteger in java ?
java.util.concurrent.atomic.AtomicInteger  provides you with int value that is updated atomically. i.e. we can use these classes without any explicit synchronization in multithreading environment, because any operation done on these classes is thread safe.



1.1) AtomicInteger constructors >
  • AtomicInteger()
Creates a new AtomicInteger and is initialized to 0.

Example >
AtomicInteger atomicInteger =new AtomicInteger();
We have created a new AtomicInteger and it is initialized to 0.

  • AtomicInteger(int initialValue)
Creates a new AtomicInteger and is initialized to specified initialValue.

Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
We have created a new AtomicInteger and it is initialized to 11.




1.2) AtomicInteger important Methods in java >
  • int get()
method returns the current value in java

Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
atomicInteger.get();
Method will return 11.

  • void set(int newValue)
Sets to newValue.

Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
atomicInteger.set(12);
Method will set return atomicInteger to 12.

  • int getAndSet(int newValue)
Sets to newValue and returns the old value.

Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
atomicInteger.getAndSet(12);
Method will set return atomicInteger to 12. And return 11.

  • boolean compareAndSet(int expect, int update)
Compare with expect, if equal, set to update and return true.
Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
atomicInteger.compareAndSet(11, 12);
Now, in call to  compareAndSet method first parameter [i.e. 11] is equal to original value, so method will set AtomicInteger to 12.
And returns true if value was successfully set.

1.3) Addition methods of AtomicInteger  >
  • int addAndGet(int value)
adds value to the current value. And return updated value.

Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
atomicInteger.addAndGet(4);
adds 4 to the current value. And return 15.


  • int incrementAndGet()
increments current value by 1. And return updated value.

Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
atomicInteger.incrementAndGet();
increments current value by 1. And return 12.


  • int getAndAdd(int value)
Method return current value. And adds value to the current value.
Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
atomicInteger.getAndAdd(4);
Method return 11. And adds 4 to 11.


  • int getAndIncrement()
Method return current value. And increments current value by 1.
Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
atomicInteger.getAndIncrement();
Method return 11. And increments 11 by 1.



1.4) Subtraction methods of AtomicInteger >
  • int decrementAndGet()
decrements current value by 1. And return updated value.

Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
atomicInteger.decrementAndGet();
decrements current value by 1. And return 10.


  • int getAndDecrement()
Method return current value. And decrements current value by 1.
Example >
AtomicInteger atomicInteger =new AtomicInteger(11);
atomicInteger.getAndDecrement();
Method return 11. And decrements 11 by 1.





2) Example/Program to demonstrate usage of java.util.concurrent.atomic.AtomicInteger in java>
package AtomicInteger;
import java.util.concurrent.atomic.AtomicInteger;
class MyRunnable implements Runnable{
  
   public void run(){
          for(int i=0;i<2;i++){
                 System.out.println("ThreadName="+Thread.currentThread().getName()
                       +" > "+ AtomicIntegerExample.sharedAtomicInteger.incrementAndGet());
          }         
         
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
/**
* Main class
*/
public class AtomicIntegerExample {
  
   //Create a new AtomicInteger and is initialized to 0.
   static AtomicInteger sharedAtomicInteger =new AtomicInteger();
  
   public static void main(String...args) throws InterruptedException{
          MyRunnable runnable=new MyRunnable();
          Thread thread1=new Thread(runnable,"Thread-1");
          Thread thread2=new Thread(runnable,"Thread-2");
          thread1.start();
          thread2.start();
         
          Thread.sleep(1000); //delay to ensure Thread-1 and Thread-2 finish
          System.out.println("After completion of both threads, "
                       + "sharedAtomicInteger = "+sharedAtomicInteger);
   }
}
/*OUTPUT
ThreadName=Thread-1 > 1
ThreadName=Thread-2 > 2
ThreadName=Thread-1 > 3
ThreadName=Thread-2 > 4
After completion of both threads, sharedAtomicInteger = 4
*/


In the program, a static AtomicInteger is created with name sharedAtomicInteger and is initialized to 0.  Then, Thread-1 and Thread-2 atomically increments sharedAtomicInteger  inside run( ) method using incrementAndGet() method [incrementAndGet() method increments current value by 1. And return updated value].
Here, sharedAtomicInteger  being AtomicInteger prevents two threads from writing to it at the same time.

2.1) Occasionally output may be different >
/*OUTPUT
ThreadName=Thread-2 > 1
ThreadName=Thread-2 > 3
ThreadName=Thread-1 > 2
ThreadName=Thread-1 > 4
After completion of both threads, sharedAtomicInteger = 4
*/

sharedAtomicInteger is incremented atomically, but sysout statements have executed out of order.



3) Program to show Consequences of using Integer in place of AtomicInteger in java >
class MyRunnable implements Runnable{
  
   public void run(){
          for(int i=0;i<2;i++){
                 System.out.println("ThreadName="+Thread.currentThread().getName()
                              +" > "+
                              ++sharedIntegerExample.sharedInteger);
          }         
         
   }
}
/**
* Main class
*/
public class sharedIntegerExample {
  
   //Create a new Integer and initialize with 0.
   static Integer sharedInteger =new Integer(0);
  
   public static void main(String...args) throws InterruptedException{
          MyRunnable runnable=new MyRunnable();
          Thread thread1=new Thread(runnable,"Thread-1");
          Thread thread2=new Thread(runnable,"Thread-2");
          thread1.start();
          thread2.start();
         
          Thread.sleep(1000); //delay to ensure Thread-1 and Thread-2 finish
          System.out.println("After completion of both threads, "
                       + "sharedInteger = "+sharedInteger);
   }
}
/*OUTPUT
ThreadName=Thread-2 > 1
ThreadName=Thread-1 > 1
ThreadName=Thread-1 > 3
ThreadName=Thread-2 > 2
After completion of both threads, sharedInteger = 3
*/

Integer class is not thread safe so two threads updated sharedInteger out of order.
So at end of program sharedInteger’s value was 3, whereas it should have been 4 because sharedInteger was initialized to 0 and was incremented 4 times.

So in this thread concurrency tutorial we learned what is java.util.concurrent.atomic.AtomicInteger in java with program and examples. We learned important methods of AtomicInteger like getAndSet, compareAndSet, incrementAndGet, getAndAdd, getAndIncrement, decrementAndGet, getAndDecrement and how to use them in thread concurrency in java.



Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

Executor framework in thread concurrency in java >

Executor and ExecutorService framework in java




Atomic operations in thread concurrency in java >

Atomic operations in java


AtomicInteger in java

Implementation of custom/own AtomicInteger in java


AtomicLong in java

Implementation of custom/own AtomicLong in java


AtomicBoolean in java




Semaphore in thread concurrency in java >

Semaphore in java


Phaser in thread concurrency in java >

Phaser in java


eEdit
Must read for you :