This post will look into the 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 a thread-safe operation in Java. To perform atomic operations on an integer counter, we have to synchronize every access-point to that counter, which will have a 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() updates the current value with the results of applying the given function. For more details on these methods, check out 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 the getAndIncrement() method.

Download Code

Output (may vary):

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

Performance Test

Following 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):

The time taken by AtomicInteger (in nanoseconds): 2513303610
The time taken by synchronized int (in nanoseconds): 8465038962
The 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 the AtomicBoolean and AtomicLong class, representing a boolean and a long value that may be updated atomically, respectively.

That’s all about the AtomicInteger class in Java.