AtomicInteger Class in Java

In this post, we will look into AtomicInteger class in Java which can be used as an atomic integer counter in multi-threaded environments that can be accessed by several threads concurrently.

 
We know that incrementing a counter is not an thread safe operation in Java. In order to perform atomic operations on an integer counter, we have to synchronize every access-point to that counter, which will have significant performance impact.

 
AtomicInteger class provides thread safe operations on an integer counter that is accessed by different threads simultaneously, without using synchronization or heavily impacting the performance. AtomicInteger class has many utility methods which all are thread safe, as shown below:

 

  1. y = atomic.get(); is equivalent to y = i;
     
  2. y = atomic.incrementAndGet(); is equivalent to y = ++i;
     
  3. y = atomic.getAndIncrement(); is equivalent to y = i++;
     
  4. y = atomic.decrementAndGet(); is equivalent to y = --i;
     
  5. y = atomic.getAndDecrement(); is equivalent to y = i--;
     
  6. y = atomic.addAndGet(x); is equivalent to i = i + x; y = i;
     
  7. y = atomic.getAndAdd(x); is equivalent to y = i; i = i + x;
     
  8. atomic.set(x); is equivalent to i = x;
     
  9. y = atomic.getAndSet(x); is equivalent to y = i; i = i + x;

 
UPDATE – Java 8 added many new functions to the AtomicInteger class, such as getAndUpdate(), updateAndGet(), getAndAccumulate(), accumulateAndGet(), which updates the current value with the results of applying the given function. More details on these methods can be seen in Java documentation.

 
Here’s a Java program that demonstrates the working of the AtomicInteger class where we have created three threads to update an AtomicInteger counter with the help of getAndIncrement() method.

 

Download

Output (may vary):

Thread-0# 1
Thread-2# 3
Thread-1# 2

 

Performance Test:

Below is another simple Java program that measures the time taken to update an AtomicInteger, a synchronized int and a simple int:

 

Download   Run Code

Output (may vary):

Time taken by AtomicInteger (in nanoseconds): 2513303610
Time taken by synchronized int (in nanoseconds): 8465038962
Time taken by int (in nanoseconds): 26130822

 
Test Result: AtomicInteger performs better than a synchronized int.

 
Similar to AtomicInteger, java.util.concurrent.atomic package also provides AtomicBoolean and AtomicLong class which represents an a boolean and a long value that may be updated atomically respectively.

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz