Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Java Java and Cryptography Mastery Series — Extended Java Programming Java Tutorial Module 19 - Advanced Collections and Concurrency

Java AtomicInteger for Lock Free Thread Safe Counter

Reviewed & accurate
AI Summary

Introduction

The Java AtomicInteger class joined the JDK in Java 5 (2004) as part of JSR 166, the original java.util.concurrent.atomic package. It is a reference type wrapping an int that supports atomic read-modify-write operations backed by compare-and-swap (CAS) instructions on the underlying hardware. AtomicInteger makes it possible to build lock-free counters, sequence generators, and statistics accumulators without resorting to synchronised blocks.

For a Java learner, the java atomicinteger primitive is the right tool whenever you have a single integer variable that many threads update and you want to avoid the contention and overhead of a lock. The classic examples are request counters, sequence number generators, and concurrent statistics. This post walks through the CAS mechanics, demonstrates a thread-safe hit counter, and shows how to use accumulateAndGet for non-trivial update functions.

What is Java AtomicInteger?

The Java AtomicInteger class is a holder for an int value that supports atomic operations. The class exposes get, set, getAndSet, compareAndSet, getAndIncrement, incrementAndGet, getAndAdd, addAndGet, getAndDecrement, decrementAndGet, getAndUpdate, updateAndGet, getAndAccumulate, and accumulateAndGet. The basic operations (get, set, getAndSet) are atomic because the underlying int field is volatile; the increment, add, decrement, and update operations use a CAS loop to atomically read, compute, and write.

Conceptually, AtomicInteger is the lock-free counterpart of an int field wrapped in synchronised accessors. For simple operations like "increment", the CAS loop in incrementAndGet is faster than a lock under moderate contention because it avoids the context-switch cost of acquiring and releasing a monitor. Under extreme contention (many threads all hitting the same AtomicInteger), the CAS loop can degrade into retry storms, and a LongAdder is the better choice.

AtomicInteger is distinct from synchronised counters in two important ways: it has no condition queue (you cannot await a value), and it has no fairness (the CAS loop retries until it succeeds, with no FIFO order among threads). For coordination beyond atomic updates, you need a lock or a synchroniser.

How Java AtomicInteger Works - Step by Step

Step 1: Construction. You write new AtomicInteger(0) or new AtomicInteger(42). The value is stored in a volatile int field annotated with the value-based memory semantics.

Step 2: get and set. get reads the volatile field; set writes it. Both are atomic because of the volatile guarantee; both establish happens-before relationships between threads.

Step 3: compareAndSet(expected, update). The CAS atomically compares the current value with expected; if they match, the value is set to update and the call returns true. If they do not match, the value is unchanged and the call returns false. CAS is the building block for all higher-level atomic operations.

Step 4: getAndIncrement. Internally, this is a CAS loop: read the current value v, attempt CAS(v, v+1), if it succeeds return v, if it fails retry with the new current value. The loop guarantees atomic increment even under concurrent updates. The companion incrementAndGet runs the same loop but returns the post-increment value, which is the value you want when you need the new total rather than the previous snapshot.

Step 5: updateAndGet(updateFunction) and getAndUpdate(updateFunction). These take an IntUnaryOperator and apply it atomically; the difference is whether the returned value is the pre-update or post-update value. The operator must be side-effect free and fast because the CAS loop may call it multiple times if other threads update concurrently. A common use is to clamp a value to a range with a lambda such as v -> Math.max(0, Math.min(v, 100)) that bounds the counter to the interval [0, 100] without ever observing an out-of-range value.

Step 6: accumulateAndGet(x, accumulatorFunction) and getAndAccumulate. These take a value and an IntBinaryOperator, applying it like (current, x) -> result. The classic use is to compute a running max or min atomically.

Java Program for AtomicInteger

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerDemo {

    static final class HitCounter {
        private final AtomicInteger hits = new AtomicInteger(0);

        void record() {
            hits.getAndIncrement();
        }

        int get() {
            return hits.get();
        }

        void reset() {
            hits.set(0);
        }
    }

    static final class MaxTracker {
        private final AtomicInteger max = new AtomicInteger(Integer.MIN_VALUE);

        void observe(int value) {
            max.accumulateAndGet(value, Math::max);
        }

        int get() {
            return max.get();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        HitCounter counter = new HitCounter();
        MaxTracker tracker = new MaxTracker();

        int threads = 8;
        int perThread = 10000;
        ExecutorService pool = Executors.newFixedThreadPool(threads);

        for (int t = 0; t < threads; t++) {
            final int id = t;
            pool.submit(() -> {
                for (int i = 0; i < perThread; i++) {
                    counter.record();
                    tracker.observe(id * perThread + i);
                }
            });
        }

        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);

        System.out.println("total hits: " + counter.get());
        System.out.println("max observed: " + tracker.get());
        System.out.println("expected hits: " + (threads * perThread));
    }
}

Code Explanation - Line by Line

The HitCounter class wraps an AtomicInteger initialised to zero. The record method calls getAndIncrement, which is the atomic equivalent of i++. Because getAndIncrement uses a CAS loop, the increment is guaranteed to happen exactly once per call even when many threads call it concurrently. The get method just reads the volatile field.

The MaxTracker class wraps an AtomicInteger initialised to Integer.MIN_VALUE. The observe method calls accumulateAndGet(value, Math::max), which is the atomic equivalent of "if (value > max) max = value". The Math::max reference is the IntBinaryOperator that picks the larger of the two arguments; the CAS loop retries the compare-and-swap until the current value and the new value have been combined successfully. If a competing thread updates the maximum between the read and the CAS, the loop re-reads the new current value and re-applies the operator; the operator is called at most a few times per call under normal contention.

The reset method in HitCounter is included to show that set is just a volatile write; it does not use CAS because it does not need to atomically combine with the previous value. Use set when you want to overwrite the value unconditionally; use compareAndSet when you want to overwrite only if the previous value matches an expected snapshot. This distinction matters for state machines where you must not clobber a transition another thread just made.

The main method submits 8 tasks of 10000 iterations each to a thread pool. Each iteration records a hit and observes a value derived from the thread id and the loop counter. The total expected hits is 8 times 10000 = 80000, and the max observed value is 7 times 10000 + 9999 = 79999 (the last value of the last thread).

The pool shutdown waits up to 5 seconds for the threads to finish, then prints the total hits, the max observed, and the expected hits. If AtomicInteger were not used, a plain int counter would have lost increments due to the read-modify-write race, and the total would have been less than 80000; the max would have been unreliable because the comparison and assignment are not atomic.

Sample Input and Output

Input:
  8 threads, each calls record() 10000 times and observes 10000 distinct values

Output:
  total hits: 80000
  max observed: 79999
  expected hits: 80000

The total hits match the expected count exactly because each increment is atomic. The max observed is the largest of the 80000 observed values, which is the last value observed by thread 7.

Common Mistakes to Avoid

Mistake 1: Treating incrementAndGet and getAndIncrement as interchangeable. They are both atomic, but they return different values: getAndIncrement returns the pre-increment value, incrementAndGet returns the post-increment value. Mixing them up leads to off-by-one bugs in code that uses the returned value.

Mistake 2: Using multiple AtomicIntegers to represent a multi-field state. CAS only updates one variable atomically; if you have two AtomicIntegers that must stay consistent with each other, you cannot update both atomically with separate CAS calls. Use an AtomicReference to a record (immutable holder) instead.

Mistake 3: Long-running functions in updateAndGet. The IntUnaryOperator passed to updateAndGet may be called multiple times by the CAS loop. If the function is slow or has side effects, the loop's retries amplify the cost; keep the function fast and pure.

Mistake 4: AtomicInteger for high-contention counters. Under extreme contention (hundreds of threads all hitting the same counter), the CAS loop retries so often that throughput collapses. LongAdder is the right choice for that workload; it shards the counter across cells and combines them on read.

Real-World Applications

Request counters. Web frameworks use AtomicInteger to count requests served, errors, and cache hits. The counter is updated on every request and read for metrics endpoints; AtomicInteger keeps the count consistent without lock contention.

Sequence number generators. Database-style sequence IDs are generated with an AtomicInteger that increments for each new row; the atomic increment guarantees uniqueness across threads.

Statistics accumulators. Latency histograms and percentile trackers use AtomicInteger fields to count how many requests fell into each bucket; the buckets are updated concurrently from many threads.

Stream and parallel pipeline state. The Streams API uses AtomicInteger internally for some split-task counters; the lock-free update is critical for parallel performance.

Lock-free data structure internals. ConcurrentSkipListMap, NonBlockingHashMap, and other lock-free structures use AtomicInteger fields to track size and version; CAS loops maintain the invariants. Each insertion publishes a new node by CAS-ing the previous tail pointer to the new node, and the size counter is updated separately with its own CAS.

Resource quotas. Thread pools, file descriptor pools, and rate limiters use AtomicInteger to track the in-flight count of permits handed out; the count is incremented on acquire and decremented on release, and a ceiling check rejects new acquisitions when the count would exceed the quota. This is lighter than a Semaphore when the wait semantics are not required.

Conclusion

AtomicInteger wraps an int with volatile semantics and CAS-based read-modify-write operations, making it the right tool for lock-free counters, sequences, and statistics. For moderate contention it outperforms synchronised counters; for extreme contention, LongAdder is the better choice. The next topics worth studying are AtomicLong for 64-bit counters, AtomicReference for atomic object swaps, and LongAdder for high-contention counters.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments