What is AtomicInteger class and how it works internally

Carvia Tech | May 19, 2019 | 2 min read | 183 views | Multithreading and Concurrency

AtomicInteger uses combination of volatile & CAS (compare and swap) to achieve thread-safety for Integer Counter. It is non-blocking in nature and thus highly usable in writing high throughput concurrent data structures that can be used under low to moderate thread contention.


In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a given new value. This is done as a single atomic operation. The atomicity guarantees that the new value is calculated based on up-to-date information.

Since the compare-and-swap occurs (or appears to occur) instantaneously, if another process updates the location while we are in-progress, the compare-and-swap is guaranteed to fail.

Thread Contention

Essentially thread contention is a condition where one thread is waiting for a lock/object that is currently being held by another thread. Waiting thread, thus cannot use that object until the other thread has unlocked that particular object.

How is volatile different from AtomicInteger

Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using synchronized code block. So the visibility of volatile field is guaranteed by the JMM.

AtomicInteger class stores its value field in a volatile variable, thus it is a decorator over the traditional volatile variable, but it provides unique non-blocking mechanism for updating the value after requiring the hardware level support for CAS (compare and set/swap). Under low to moderate thread contention, atomic updates provides higher throughput compared to synchronized blocking increment operation.

Here is the implementation for getAndIncrement() method of AtomicInteger Class (as of Java 7).
    public final int getAndIncrement() {
            for (;;) {
                int current = get();
                int next = current + 1;
                if (compareAndSet(current, next))
                    return current;

You can see that no lock is acquired to increment the value, rather CAS is used inside infinite loop to update the new value, that’s why it can be used to write scalable application where thread contention is low to medium.

General Advice

Use synchronized mechanism wherever thread contention is high i.e. multiple threads writes to the shared variable at the same point in time. Use AtomicInteger where thread contention is low to moderate to build highly scalable applications.

AtomicInteger class is best candidate for implementing thread-safe counters in your application.

Multithreading and Concurrency:
  1. How will you handle ConcurrentModificationException in Java
  2. Producer Consumer Problem using Blocking Queue in Java
  3. What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications
  4. What is difference between Callable and Runnable Interface?
  5. Discuss internals of a ConcurrentHashmap (CHM) in Java
  6. What is Immutable Class. Why would you choose it? How would you make a class immutable?
  7. Can the keys in HashMap be mutable
See all articles in Multithreading and Concurrency
Top articles in this category:
  1. What is Deadlock in Java? How to troubleshoot and how to avoid deadlock
  2. What is Immutable Class. Why would you choose it? How would you make a class immutable?
  3. Discuss internals of a ConcurrentHashmap (CHM) in Java
  4. How to implement Thread pool in Java without executor framework
  5. Design an Immutable class that has an java.util.Date member
  6. What are four principles of OOP, How aggregation is different than Composition?
  7. What is purpose of Collections.unmodifiableCollection

Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 month ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info