Implementation of custom/own AtomicInteger in java



In this thread concurrency tutorial we will learn how to implement custom/own AtomicInteger in java with program and examples. In previous tutorial we read how to use AtomicInteger in java. This tutorial intends you provides you basic functionality of AtomicInteger using your own java code

We will write java code for important methods of your custom/own 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 AtomicIntegerCustom in java?
  • 1.1) AtomicIntegerCustom constructors >
  • AtomicIntegerCustom()
  • AtomicIntegerCustom(int initialValue)
  • 1.2) AtomicIntegerCustom important Methods >
  • int get()
  • void set(int newValue)
  • int getAndSet(int newValue)
  • boolean compareAndSet(int expect, int update)
  • 1.3) Addition methods of custom/own AtomicInteger in java >
  • int addAndGet(int value)
  • int incrementAndGet()
  • int getAndAdd(int value)
  • int getAndIncrement()
  • 1.4) Subtraction methods of custom/own AtomicInteger in java >
  • int decrementAndGet()
  • int getAndDecrement()
  • 2) Custom AtomicInteger’s code >
  • 3) Program to demonstrate usage of AtomicIntegerCustom >
  • 3.1) Occasionally output may be different >


1) What is AtomicIntegerCustom in java ?
In previous tutorial we read how to use AtomicInteger in java. In this post we will be implementing custom/own AtomicInteger. This tutorial intends you give you basic functionality of AtomicInteger using your own java code

AtomicIntegerCustom  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) AtomicIntegerCustom constructors >
  • AtomicIntegerCustom()
Creates a new AtomicIntegerCustom and is initialized to 0.

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

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

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




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

Example >
AtomicIntegerCustom atomicIntegerCustom =new AtomicIntegerCustom(11);
atomicIntegerCustom.get();
Method will return 11.

  • void set(int newValue)
Sets to newValue.

Example >
AtomicIntegerCustom atomicIntegerCustom =new AtomicIntegerCustom(11);
atomicIntegerCustom.set(12);
Method will set return AtomicIntegerCustom to 12.

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

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

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

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

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


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

Example >
AtomicIntegerCustom atomicIntegerCustom =new AtomicIntegerCustom(11);
atomicIntegerCustom.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 >
AtomicIntegerCustom atomicIntegerCustom =new AtomicIntegerCustom(11);
atomicIntegerCustom.getAndAdd(4);
Method return 11. And adds 4 to 11.


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



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

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


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



2) Custom AtomicInteger’s java code >
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal .
* All Contents are copyrighted and must not be reproduced in any form.
*
* AtomicIntegerCustom provides you with int value that is updated atomically.
*/
class AtomicIntegerCustom{
   int currentValue;
   int previousValue;
  
   //AtomicintCustom constructors >
   /**
   * Creates a new AtomicInteger and is initialized to 0.
   */
   public AtomicIntegerCustom(){
          currentValue=0;
   }
  
   /**
   * Creates a new AtomicIntegerCustom and is initialized to specified initialValue.
   * @param initialValue
   */
   public AtomicIntegerCustom(int initialValue){
          currentValue=initialValue;
   }
  
   //AtomicIntegerCustom  important Methods >
   /**
   * method returns the current value
   *
   */
   public synchronized int get(){
          return currentValue;
   }
  
   /**
   * Sets to newValue.
   */
   public synchronized void set(int newValue){
          currentValue=newValue;
   }
  
   /**
   * Sets to newValue and returns the old value.
   */
   public synchronized int getAndSet(int newValue){
          previousValue=currentValue;
          currentValue=newValue;
          return previousValue;
   }
  
   /**
   * Compare with expect, if equal, set to update and return true.
   */
   public synchronized boolean compareAndSet(int expect, int update){
          if(currentValue == expect){
                 currentValue=update;
                 return true;
          }
          else
                 return false;
   }
  
   //Addition methods >
   /**
   * adds value to the current value. And return updated value.
   */
   public synchronized int addAndGet(int value){
          return currentValue+=value;
   }
  
   /**
   * increments current value by 1. And return updated value.
   */
   public synchronized int incrementAndGet(){
          return ++currentValue;
   }
  
   /**
   * Method return current value. And adds value to the current value.
   */
   public synchronized int getAndAdd(int value){
          previousValue=currentValue;
          currentValue+=value;
          return previousValue;
   }
  
   /**
   * Method return current value. And increments current value by 1.
   *
   */
   public synchronized int getAndIncrement(){
          return currentValue++;
   }
  
   //Subtraction methods >
   /**
   * decrements current value by 1. And return updated value.
   */
   public synchronized int decrementAndGet(){
          return --currentValue;
   }
  
   /**
   * Method return current value. And decrements current value by 1.
   */
   public synchronized int getAndDecrement(){
          return currentValue--;
   }
  
   @Override
   public String toString() {
          return "AtomicIntegerCustom = " + currentValue ;
   }  
}


3) Example/Program to demonstrate usage of AtomicIntegerCustom in java(We will use above written java code of custom AtomicInteger ) >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal .
* All Contents are copyrighted and must not be reproduced in any form.
*
* AtomicIntegerCustom provides you with int value that is updated atomically.
*/
class AtomicIntegerCustom{
   int currentValue;
   int previousValue;
  
   //AtomicIntegerCustom constructors >
   /**
   * Creates a new AtomicInteger and is initialized to 0.
   */
   public AtomicIntegerCustom(){
          currentValue=0;
   }
  
   /**
   * Creates a new AtomicInteger and is initialized to specified initialValue.
   * @param initialValue
   */
   public AtomicIntegerCustom(int initialValue){
          currentValue=initialValue;
   }
  
   //AtomicIntegerCustom important Methods >
   /**
   * method returns the current value
   *
   */
   public synchronized int get(){
          return currentValue;
   }
  
   /**
   * Sets to newValue.
   */
   public synchronized void set(int newValue){
          currentValue=newValue;
   }
  
   /**
   * Sets to newValue and returns the old value.
   */
   public synchronized int getAndSet(int newValue){
          previousValue=currentValue;
          currentValue=newValue;
          return previousValue;
   }
  
   /**
   * Compare with expect, if equal, set to update and return true.
   */
   public synchronized boolean compareAndSet(int expect, int update){
          if(currentValue == expect){
                 currentValue=update;
                 return true;
          }
          else
                 return false;
   }
  
   //Addition methods >
   /**
   * adds value to the current value. And return updated value.
   */
   public synchronized int addAndGet(int value){
          return currentValue+=value;
   }
  
   /**
   * increments current value by 1. And return updated value.
   */
   public synchronized int incrementAndGet(){
          return ++currentValue;
   }
  
   /**
   * Method return current value. And adds value to the current value.
   */
   public synchronized int getAndAdd(int value){
          previousValue=currentValue;
          currentValue+=value;
          return previousValue;
   }
  
   /**
   * Method return current value. And increments current value by 1.
   *
   */
   public synchronized int getAndIncrement(){
          return currentValue++;
   }
  
   //Subtraction methods >
   /**
   * decrements current value by 1. And return updated value.
   */
   public synchronized int decrementAndGet(){
          return --currentValue;
   }
  
   /**
   * Method return current value. And decrements current value by 1.
   */
   public synchronized int getAndDecrement(){
          return currentValue--;
   }
  
   @Override
   public String toString() {
          return "AtomicIntegerCustom = " + currentValue ;
   }  
}
/**
* Main class
*/
public class AtomicIntegerCustomExample {
  
   //Create a new AtomicIntegerCustom and is initialized with 0.
   static AtomicIntegerCustom sharedAtomicIntegerCustom =new AtomicIntegerCustom();
  
   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, "
                       + "sharedAtomicIntegerCustom = "+sharedAtomicIntegerCustom);
   }
}
class MyRunnable implements Runnable{
  
   public void run(){
          for(int i=0;i<2;i++){
                 System.out.println("ThreadName="+Thread.currentThread().getName()
                              +" > "+
   AtomicIntegerCustomExample.sharedAtomicIntegerCustom.incrementAndGet());
          }         
         
   }
}
/*OUTPUT
ThreadName=Thread-1 > 1
ThreadName=Thread-2 > 2
ThreadName=Thread-1 > 3
ThreadName=Thread-2 > 4
After completion of both threads, sharedAtomicIntegerCustom = 4
*/
/*OUTPUT
ThreadName=Thread-2 > 1
ThreadName=Thread-2 > 3
ThreadName=Thread-1 > 2
ThreadName=Thread-1 > 4
After completion of both threads, sharedAtomicIntegerCustom = 4
*/


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

3.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, sharedAtomicIntegerCustom = 4
*/

sharedAtomicIntegerCustom is incremented atomically, but sysout statements have executed out of order in java.


So in this thread concurrency tutorial we learned how to implement custom/own AtomicInteger java with program and examples. In previous tutorial we read how to use AtomicInteger in java. This tutorial provides you basic functionality of AtomicInteger using your own java code.

We wrote java code for important methods of your custom/own AtomicInteger like getAndSet, compareAndSet, incrementAndGet, getAndAdd, getAndIncrement, decrementAndGet, getAndDecrement and used 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



Lock and Reentrant Locks in thread concurrency in java >

Locks and ReEntrantLocks in java

Implementation of custom/own Lock and ReEntrantLock in java


ReentrantLock class provides implementation of Lock’s newCondition() method - description and solving producer consumer program using this method



Fork/Join framework in thread concurrency in java >

Fork/Join Framework - Parallel programming in java


eEdit
Must read for you :