AtomicInteger in Java

Definition of AtomicInteger:

AtomicInteger is used primarily in multi-threaded environment when we need to process thread safe operations on an integer value without using synchronized keyword. Retrieving and assigning operations on primitive type int are already atomic but AtomicInteger provides many other operations which are not atomic. AtomicInteger is a wrapper class for int.

  • AtomicInteger works on CAS(compare and swap) algorithm. CAS is a machine instruction.
  • CAS algorithm compares the contents of a memory location to a given value and only if they are same, then it modifies the contents of that memory location to a given new value, this complete operation is done as a single atomic operation.
  • CAS belongs to CPU so it is fast.

Package: java.util.concurrent.atomic

Since: JDK 1.5

Main methods of AtomicInteger:

  • addAndGet(int n)
  • getAndAdd(int n)
  • incrementAndGet()
  • getAndIncrement()
  • compareAndSet(int expect, int update)

Beside atomicity, AtomicInteger can be used as a mutable version of Integer for instance in Maps as values.


AtomicInteger is fast and more readable than synchronization.

Source: JavaDoc

Java Professional with rich experience in Java development.
– Designing and developing high-volume, low-latency applications with high-availability and performance.
– Writing well designed, robust and efficient code.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By :