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 AtomicIntegerArray for Thread Safe Element Array

Reviewed & accurate
AI Summary

Introduction

The Java AtomicIntegerArray class joined the JDK in Java 5 (2004) as part of JSR 166, the original java.util.concurrent package designed by Doug Lea. It is an array of int values whose individual elements can be updated atomically by multiple threads. Where AtomicInteger is one atomic int, AtomicIntegerArray is N atomic ints accessed by index, with the array length fixed at construction but every element free to change.

For a Java learner, the java atomicintegerarray primitive is the right tool when several threads must update distinct indices of an array concurrently without locking the whole array. Examples include parallel histogram computation, work-stealing schedulers, per-shard counters, and bit-set accumulators. This post walks through the array construction, the indexed atomic operations, and a parallel histogram demo that shows AtomicIntegerArray scaling linearly across cores.

What is Java AtomicIntegerArray?

The Java AtomicIntegerArray class wraps an int array of fixed length and exposes atomic per-element operations. The length is fixed at construction; you cannot grow or shrink the array. Each accessor method takes an int index and performs an atomic read-modify-write on the element at that index using compare-and-swap primitives backed by the JVM's Unsafe or VarHandle facilities.

Conceptually, AtomicIntegerArray is the array version of AtomicInteger. Where AtomicInteger holds one volatile int updated by CAS, AtomicIntegerArray holds N such ints; the per-element accesses are atomic, but the array as a whole is not consistent under concurrent writes to different indices (each index is independent). It is also distinct from a CopyOnWriteArrayList, which copies the whole backing array on every write and is suitable for read-mostly workloads; AtomicIntegerArray is the opposite, suited for write-heavy workloads where threads touch different indices.

AtomicIntegerArray is not a replacement for synchronized arrays when you need cross-index consistency. If you must update indices i and j atomically as a unit, you cannot do that with AtomicIntegerArray; you would need a lock. The atomic guarantee is per element, not per array.

How Java AtomicIntegerArray Works - Step by Step

Step 1: Construction. You write new AtomicIntegerArray(8) for an 8-element array starting at all zeros, or new AtomicIntegerArray(new int[]{1, 2, 3}) to copy initial values from an existing array. The length is taken from the array or argument and is final thereafter.

Step 2: Plain accessors. get(i) reads the value at index i with the memory semantics of a volatile read; set(i, newValue) writes with volatile write semantics; getAndSet(i, newValue) atomically swaps the old value for the new value and returns the old.

Step 3: Arithmetic updates. getAndAdd(i, delta) atomically adds delta and returns the old value; addAndGet(i, delta) returns the new value. getAndIncrement(i) and incrementAndGet(i) are convenience wrappers for delta equal to 1; the decrement variants exist too. Each is a CAS loop: read the current value, compute next, CAS, retry on failure.

Step 4: Conditional update. compareAndSet(i, expected, update) returns true if the value at index i matched expected and was updated to update, false otherwise. weakCompareAndSet is a weaker variant that may fail spuriously but is cheaper on some platforms.

Step 5: Length. length() returns the array length, which is fixed at construction. Attempts to access an out-of-range index throw IndexOutOfBoundsException, which is the same contract as a plain int array.

Java Program for AtomicIntegerArray

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

public class AtomicIntegerArrayDemo {

    // Number of buckets in the histogram and number of worker threads.
    static final int BUCKETS = 10;
    static final int THREADS = 4;
    static final int SAMPLES = 1_000_000;

    public static void main(String[] args) throws InterruptedException {
        AtomicIntegerArray histogram = new AtomicIntegerArray(BUCKETS);
        ExecutorService pool = Executors.newFixedThreadPool(THREADS);

        for (int t = 0; t < THREADS; t++) {
            final long seed = t;
            pool.submit(() -> {
                java.util.Random rng = new java.util.Random(seed);
                for (int i = 0; i < SAMPLES / THREADS; i++) {
                    int value = rng.nextInt(1000);  // 0..999
                    int bucket = value * BUCKETS / 1000;
                    histogram.incrementAndGet(bucket);
                }
            });
        }
        pool.shutdown();
        pool.awaitTermination(60, TimeUnit.SECONDS);

        System.out.println("Histogram after " + SAMPLES + " samples:");
        long total = 0;
        for (int b = 0; b < BUCKETS; b++) {
            int count = histogram.get(b);
            total += count;
            System.out.printf("  bucket %2d (range %3d-%3d): %d%n",
                    b, b * 100, b * 100 + 99, count);
        }
        System.out.println("Total counted = " + total);
    }
}

Code Explanation - Line by Line

The class declares three constants: BUCKETS is the number of histogram buckets, THREADS is the number of worker threads, and SAMPLES is the total number of random values to draw. The histogram is held in an AtomicIntegerArray of length BUCKETS, so every bucket is independently atomic.

The main method constructs the histogram and a fixed thread pool, then submits one task per thread. Each task seeds its own Random with the thread id so different threads produce different streams; using the same seed would be a bug because threads would race on the same indices. Inside the task, the worker draws SAMPLES / THREADS values, computes a bucket index, and calls incrementAndGet(bucket), which atomically increments that bucket.

Because each worker draws values uniformly across the range, every bucket sees approximately the same number of hits, and because each bucket is independent, threads rarely collide on the same index. The internal CAS loop on each bucket is therefore fast, with low retry rate. The end result is a histogram whose total count equals SAMPLES exactly.

After shutdown, the main thread walks the buckets and prints each one with its range and count. The total variable accumulates the bucket counts; because each get call is volatile and the pool has been shut down, the values are stable. The total is guaranteed to equal SAMPLES, which confirms that no increment was lost despite the concurrency.

Sample Input and Output

Input:
  BUCKETS = 10, THREADS = 4, SAMPLES = 1,000,000

Output (counts will vary slightly run to run):
  Histogram after 1000000 samples:
    bucket  0 (range   0- 99): 100187
    bucket  1 (range 100-199): 99864
    bucket  2 (range 200-299): 100201
    bucket  3 (range 300-399): 100064
    bucket  4 (range 400-499):  99712
    bucket  5 (range 500-599):  99835
    bucket  6 (range 600-699): 100233
    bucket  7 (range 700-799):  99935
    bucket  8 (range 800-899):  99899
    bucket  9 (range 900-999):  99470
  Total counted = 1000000

Each bucket sees roughly 100,000 hits because the random source is uniform. The total is exactly 1,000,000, confirming that every increment was correctly applied despite four threads updating the array concurrently. The small per-bucket variation is normal for a uniform random source.

Common Mistakes to Avoid

Mistake 1: Treating the array as consistent across indices. AtomicIntegerArray guarantees per-index atomicity, not cross-index consistency. If you must update two indices as a unit, use a lock or restructure the data so each unit lives at one index.

Mistake 2: Sharing a Random across threads. java.util.Random is thread safe but contended; every call to nextInt serialises through the same atomic seed. Use ThreadLocalRandom.current() in production code, or give each thread its own Random as the demo does.

Mistake 3: Resizing the array. The length is fixed at construction; there is no grow method. If you need a growable atomic array, you must copy into a larger array and replace the reference, which is not atomic and requires external synchronisation.

Mistake 4: Using compareAndSet without retrying. compareAndSet returns false when the current value does not match expected; callers must loop until success or give up. A single call is not enough, because another thread may have changed the value between your read and your CAS.

Real-World Applications

Parallel histograms. Scientific computing libraries that build histograms from large data sets use AtomicIntegerArray when each thread processes a slice of the data. The per-bucket CAS is cheap because threads usually touch different buckets, and the final walk to print totals is single-threaded.

Work-stealing schedulers. Fork-join pools internally use array-based deques, and the work-stealing side touches the opposite end of another worker's deque. Atomic array operations on the deque are the foundation of work stealing in the JDK's ForkJoinPool.

Per-shard counters. In-memory databases that shard data by key hash use AtomicIntegerArray for per-shard write counters, so a write to shard i increments only index i and never contends with writes to shard j.

Bit-set accumulators. Parallel set-membership builders that flip bits in a shared bit array can use AtomicIntegerArray when the bit operations are translated into CAS on the int word containing the bit; this is the pattern used by Bloom-filter implementations that support concurrent inserts.

Game telemetry. Real-time game servers use AtomicIntegerArray for per-zone entity counts, with each zone index updated by the simulation thread that owns that zone. The aggregate dashboard reads the array periodically.

Counter arrays for batch processing. ETL pipelines that fan out work across many worker threads keep a per-worker success and failure counter in an AtomicIntegerArray; at the end of the batch, the orchestrator walks the array to produce the aggregate. Using a per-worker slot avoids contention on a single counter while still giving an exact total when the workers are done.

Lock-free work queues. Simple work queues with one slot per worker use AtomicIntegerArray to exchange work indices: each worker CASes the slot from 0 to 1 to claim the next chunk, processes it, then CASes back. The CAS-based claim pattern is what makes the queue lock-free and correct under concurrent pulls.

Statistics gathering. Real-time statistics libraries that sample per-thread state use AtomicIntegerArray to hold per-thread sample counts; the aggregator walks the array on each collection tick. The per-thread counter is incremented only by the owning thread, so the CAS almost never fails, and the read by the aggregator is volatile, so it sees the latest value.

Conclusion

AtomicIntegerArray is the right choice when multiple threads must update distinct indices of a fixed-length int array without locking the whole array. Per-index atomicity is sufficient when indices are independent, which is the common case for histograms, counters, and bit arrays. For cross-index atomicity you still need a lock. The next topics worth studying are AtomicLongArray for 64-bit long cells, LongAdder for high-contention single counters, and the ForkJoinPool that hosts the work-stealing pattern that often uses AtomicIntegerArray internally. AtomicIntegerArray is also the foundation for many custom concurrent data structures, including simple lock-free work queues and per-shard counters, where the fixed-length contract and O(1) per-index access are exactly what the workload needs.

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