Back to Atomic Classes & CAS
Q4Question 4 of 5

How do atomic variables and concurrent collections work in Java

Answer: Atomic variables use compare-and-swap (CAS) CPU instructions to update values without locks, and concurrent collections like ConcurrentHashMap use fine-grained locking or lock-free algorithms to allow safe concurrent access from multiple threads.

Key Concepts
  • Atomic variables like AtomicInteger, AtomicLong, and AtomicReference provide lock-free thread-safe operations using compare-and-swap (CAS).
  • Compare-and-swap (CAS) is a CPU instruction that updates a value only if it matches the expected old value, retrying on failure without locking.
  • CAS avoids the overhead of synchronized blocks: no lock acquisition, no thread blocking, no context switching under low contention.
  • ConcurrentHashMap divides the map into segments and locks only the affected segment, allowing concurrent reads and writes to different keys.
  • CopyOnWriteArrayList creates a new array copy on every write, making it safe for frequent reads and rare writes like configuration lists.
  • Under high contention, CAS performance degrades because threads retry in a spin loop, and LongAdder or LongAccumulator should be used instead.
  • Atomic classes live in java.util.concurrent.atomic and concurrent collections live in java.util.concurrent.

Definition

Atomic variables use compare-and-swap (CAS) CPU instructions to update values without locks, and concurrent collections like ConcurrentHashMap use fine-grained locking or lock-free algorithms to allow safe concurrent access from multiple threads.
  • Atomic variable is a thread-safe wrapper around a value (int, long, reference) that uses CAS instead of synchronized blocks, avoiding lock overhead.
  • Compare-and-swap (CAS) is a CPU-level instruction that reads the current value, compares it to an expected value, and writes the new value only if they match, all in a single atomic operation.
  • ConcurrentHashMap is a thread-safe map that uses fine-grained bucket-level locking (Java 8+) instead of locking the entire map, allowing concurrent reads and writes to different segments.
  • CopyOnWriteArrayList is a thread-safe list that creates a new copy of the underlying array on every mutation, making reads lock-free and writes expensive.
  • LongAdder is a high-performance alternative to AtomicLong for counters under high contention, using multiple cells that are summed when the total is read.

Think of the deposit counter at National Bank of India. With synchronized (a single lock), there is one counter window: every customer lines up, and only one is served at a time. With CAS (atomic variable), there is no line: a customer walks up, checks the current number on the display board (expected value), fills out their form with the next number (new value), and tries to update the board. If someone else updated it first, the customer reads the new number and tries again. Nobody waits in a queue. ConcurrentHashMap is like having separate counters for each department (savings, loans, forex): multiple customers are served simultaneously because they go to different counters.

Understanding the Concepts

What are atomic variables in Java?

Atomic variables are thread-safe wrappers around primitive values and references that use CAS (compare-and-swap) instead of locks. They live in the java.util.concurrent.atomic package. The most commonly used classes are:

  • AtomicInteger: thread-safe int
  • AtomicLong: thread-safe long
  • AtomicBoolean: thread-safe boolean
  • AtomicReference: thread-safe object reference
  • AtomicIntegerArray, AtomicLongArray: thread-safe arrays

Atomic variables guarantee that read-modify-write operations (increment, compare-and-set, get-and-add) are atomic without using synchronized.

JAVA
package com.bank.atomic;

import java.util.concurrent.atomic.AtomicLong;
import java.math.BigDecimal;

public class AtomicBasicsDemo {
    // Thread-safe transaction counter without synchronized
    private static final AtomicLong transactionCounter = new AtomicLong(0);

    public static void main(String[] args) throws InterruptedException {
        System.out.println("=== AtomicLong as Transaction Counter ===");
        System.out.println("Initial value: " + transactionCounter.get());

        // 10 threads, each incrementing 1000 times
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    transactionCounter.incrementAndGet();
                }
            }, "counter-" + i);
            threads[i].start();
        }

        for (Thread t : threads) {
            t.join();
        }

        System.out.println("Final value: " + transactionCounter.get());
        System.out.println("Expected:    10000");
        System.out.println("No lost updates, no locks, no synchronized.");
        System.out.println();

        // Useful AtomicLong operations
        System.out.println("=== AtomicLong Operations ===");
        AtomicLong balance = new AtomicLong(500000);
        System.out.println("Balance:          " + balance.get());
        System.out.println("addAndGet(25000): " + balance.addAndGet(25000));
        System.out.println("getAndAdd(10000): " + balance.getAndAdd(10000));
        System.out.println("After getAndAdd:  " + balance.get());
        System.out.println("compareAndSet(535000, 600000): "
            + balance.compareAndSet(535000, 600000));
        System.out.println("After CAS:        " + balance.get());
    }
}
TEXT
Expected output:
=== AtomicLong as Transaction Counter ===
Initial value: 0
Final value: 10000
Expected:    10000
No lost updates, no locks, no synchronized.

=== AtomicLong Operations ===
Balance:          500000
addAndGet(25000): 525000
getAndAdd(10000): 525000
After getAndAdd:  535000
compareAndSet(535000, 600000): true
After CAS:        600000

What is compare-and-swap (CAS)?

Compare-and-swap is a CPU instruction (also called compare-and-exchange) that performs three steps atomically:

  1. Read the current value at a memory location.
  2. Compare it with an expected value.
  3. If they match, write the new value. If they do not match, do nothing.

The entire operation happens in a single CPU cycle, so no other thread can intervene between the read and the write. When the CAS fails (another thread changed the value first), the calling code retries in a loop. This retry loop is called a spin.

JAVA
package com.bank.atomic;

import java.util.concurrent.atomic.AtomicInteger;

public class CASDemo {
    private static final AtomicInteger accountBalance = new AtomicInteger(100000);

    public static void main(String[] args) {
        System.out.println("=== CAS Step by Step ===");
        System.out.println("Current balance: " + accountBalance.get());

        // Simulate a deposit of 25000 using CAS
        int expected;
        int newValue;
        boolean success;

        // Attempt 1: might succeed or fail
        expected = accountBalance.get();   // Step 1: read current value (100000)
        newValue = expected + 25000;        // Compute new value (125000)
        success = accountBalance.compareAndSet(expected, newValue);
        System.out.println();
        System.out.println("CAS attempt 1:");
        System.out.println("  Expected: " + expected);
        System.out.println("  New:      " + newValue);
        System.out.println("  Success:  " + success);
        System.out.println("  Balance:  " + accountBalance.get());

        // Attempt 2: use a wrong expected value (simulates another thread changed it)
        expected = 100000;  // Stale value, no longer current
        newValue = expected + 10000;
        success = accountBalance.compareAndSet(expected, newValue);
        System.out.println();
        System.out.println("CAS attempt 2 (stale expected value):");
        System.out.println("  Expected: " + expected);
        System.out.println("  New:      " + newValue);
        System.out.println("  Success:  " + success + " (CAS failed, value unchanged)");
        System.out.println("  Balance:  " + accountBalance.get());

        // Correct retry pattern
        System.out.println();
        System.out.println("=== CAS Retry Loop (how atomic operations work internally) ===");
        int retries = 0;
        do {
            expected = accountBalance.get();
            newValue = expected + 10000;
            success = accountBalance.compareAndSet(expected, newValue);
            retries++;
        } while (!success);
        System.out.println("  Deposited 10000 after " + retries + " attempt(s)");
        System.out.println("  Final balance: " + accountBalance.get());
    }
}
TEXT
Expected output:
=== CAS Step by Step ===
Current balance: 100000

CAS attempt 1:
  Expected: 100000
  New:      125000
  Success:  true
  Balance:  125000

CAS attempt 2 (stale expected value):
  Expected: 100000
  New:      110000
  Success:  false (CAS failed, value unchanged)
  Balance:  125000

=== CAS Retry Loop (how atomic operations work internally) ===
  Deposited 10000 after 1 attempt(s)
  Final balance: 135000

How is AtomicInteger different from synchronized?

FeaturesynchronizedAtomicInteger (CAS)
MechanismMonitor lock (mutex)CPU CAS instruction
BlockingThreads wait (BLOCKED state)Threads spin-retry (RUNNABLE state)
Context switchingYes, blocked threads are descheduledNo, spinning threads stay on CPU
Low contentionSlightly slower (lock overhead)Faster (no lock overhead)
High contentionBetter (blocked threads yield CPU)Worse (spinning wastes CPU cycles)
Deadlock riskYes, if multiple locks acquired in wrong orderNo, no locks involved
ScopeCan protect any block of codeSingle variable only
Memory visibilityGuaranteed (happens-before)Guaranteed (volatile semantics)
JAVA
package com.bank.atomic;

import java.util.concurrent.atomic.AtomicLong;

public class AtomicVsSynchronizedDemo {
    private static long synchronizedBalance = 0;
    private static final Object lock = new Object();
    private static final AtomicLong atomicBalance = new AtomicLong(0);

    private static final int THREADS = 10;
    private static final int OPS_PER_THREAD = 1_000_000;

    public static void main(String[] args) throws InterruptedException {
        // Benchmark synchronized
        long syncTime = benchmarkSynchronized();
        System.out.println("Synchronized: " + syncTime + " ms, balance = " + synchronizedBalance);

        // Benchmark AtomicLong
        long atomicTime = benchmarkAtomic();
        System.out.println("AtomicLong:   " + atomicTime + " ms, balance = " + atomicBalance.get());

        System.out.println();
        if (atomicTime < syncTime) {
            System.out.println("AtomicLong was faster by " + (syncTime - atomicTime) + " ms");
        } else {
            System.out.println("Synchronized was faster by " + (atomicTime - syncTime) + " ms");
        }
        System.out.println("Both produce correct results. Choose based on contention level.");
    }

    private static long benchmarkSynchronized() throws InterruptedException {
        synchronizedBalance = 0;
        Thread[] threads = new Thread[THREADS];
        long start = System.currentTimeMillis();

        for (int i = 0; i < THREADS; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < OPS_PER_THREAD; j++) {
                    synchronized (lock) {
                        synchronizedBalance++;
                    }
                }
            });
            threads[i].start();
        }
        for (Thread t : threads) t.join();
        return System.currentTimeMillis() - start;
    }

    private static long benchmarkAtomic() throws InterruptedException {
        atomicBalance.set(0);
        Thread[] threads = new Thread[THREADS];
        long start = System.currentTimeMillis();

        for (int i = 0; i < THREADS; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < OPS_PER_THREAD; j++) {
                    atomicBalance.incrementAndGet();
                }
            });
            threads[i].start();
        }
        for (Thread t : threads) t.join();
        return System.currentTimeMillis() - start;
    }
}
TEXT
Expected output:
Synchronized: 312 ms, balance = 10000000
AtomicLong:   198 ms, balance = 10000000

AtomicLong was faster by 114 ms
Both produce correct results. Choose based on contention level.

The numbers vary by machine, but AtomicLong is typically faster for simple increment operations because CAS avoids lock overhead and context switching.

What are concurrent collections?

Concurrent collections are thread-safe data structures in java.util.concurrent that allow multiple threads to read and write without external synchronization. The key implementations are:

  • ConcurrentHashMap: Thread-safe map with bucket-level locking.
  • CopyOnWriteArrayList: Thread-safe list, lock-free reads, copy-on-write mutations.
  • ConcurrentLinkedQueue: Lock-free thread-safe queue using CAS.
  • BlockingQueue implementations (ArrayBlockingQueue, LinkedBlockingQueue): Thread-safe queues with blocking put/take operations.
JAVA
package com.bank.atomic;

import java.util.concurrent.ConcurrentHashMap;
import java.math.BigDecimal;

public class ConcurrentCollectionsDemo {
    public static void main(String[] args) throws InterruptedException {
        // ConcurrentHashMap as account cache
        ConcurrentHashMap<String, BigDecimal> accountCache = new ConcurrentHashMap<>();

        // Multiple threads adding accounts concurrently
        Thread t1 = new Thread(() -> {
            accountCache.put("SAV2001", new BigDecimal("250000.00"));
            accountCache.put("SAV2002", new BigDecimal("180000.00"));
            System.out.println("[thread-1] Added SAV2001 and SAV2002");
        });

        Thread t2 = new Thread(() -> {
            accountCache.put("CUR3001", new BigDecimal("1500000.00"));
            accountCache.put("CUR3002", new BigDecimal("750000.00"));
            System.out.println("[thread-2] Added CUR3001 and CUR3002");
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println();
        System.out.println("Account cache (" + accountCache.size() + " entries):");
        accountCache.forEach((id, balance) ->
            System.out.println("  " + id + ": " + balance + " INR"));

        // Atomic compute operations
        System.out.println();
        System.out.println("=== Atomic Compute Operations ===");

        // computeIfAbsent: add only if key is missing
        accountCache.computeIfAbsent("SAV2003", key -> {
            System.out.println("Creating new account: " + key);
            return new BigDecimal("50000.00");
        });

        // merge: update balance atomically
        accountCache.merge("SAV2001", new BigDecimal("25000.00"), BigDecimal::add);
        System.out.println("SAV2001 after deposit: " + accountCache.get("SAV2001"));

        // compute: update with a function
        accountCache.compute("SAV2002", (key, current) ->
            current.subtract(new BigDecimal("10000.00")));
        System.out.println("SAV2002 after withdrawal: " + accountCache.get("SAV2002"));
    }
}
TEXT
Expected output:
[thread-1] Added SAV2001 and SAV2002
[thread-2] Added CUR3001 and CUR3002

Account cache (4 entries):
  CUR3001: 1500000.00 INR
  CUR3002: 750000.00 INR
  SAV2001: 250000.00 INR
  SAV2002: 180000.00 INR

=== Atomic Compute Operations ===
Creating new account: SAV2003
SAV2001 after deposit: 275000.00
SAV2002 after withdrawal: 170000.00

How is ConcurrentHashMap different from synchronized HashMap?

FeatureCollections.synchronizedMap(HashMap)ConcurrentHashMap
LockingLocks the entire map on every operationLocks only the affected bucket (Java 8+)
Read concurrencyOne reader at a time (lock required)Multiple readers without locking
Write concurrencyOne writer at a timeMultiple writers to different buckets concurrently
Null keys/valuesAllows one null key, any null valuesNo null keys or values allowed
IterationFail-fast (ConcurrentModificationException)Weakly consistent (no exception)
Atomic operationsNot available (putIfAbsent, compute, merge)Built-in atomic operations
PerformancePoor under concurrencyGood under concurrency
JAVA
package com.bank.atomic;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.math.BigDecimal;

public class ConcurrentMapComparisonDemo {
    private static final int THREADS = 10;
    private static final int OPS_PER_THREAD = 100_000;

    public static void main(String[] args) throws InterruptedException {
        // Benchmark synchronizedMap
        Map<String, BigDecimal> syncMap = Collections.synchronizedMap(new HashMap<>());
        long syncTime = benchmark(syncMap, "synchronizedMap");

        // Benchmark ConcurrentHashMap
        Map<String, BigDecimal> concurrentMap = new ConcurrentHashMap<>();
        long concurrentTime = benchmark(concurrentMap, "ConcurrentHashMap");

        System.out.println();
        System.out.println("synchronizedMap: " + syncTime + " ms");
        System.out.println("ConcurrentHashMap: " + concurrentTime + " ms");
        System.out.println("ConcurrentHashMap is typically 2-5x faster under contention.");
    }

    private static long benchmark(Map<String, BigDecimal> map, String name)
            throws InterruptedException {
        Thread[] threads = new Thread[THREADS];
        long start = System.currentTimeMillis();

        for (int i = 0; i < THREADS; i++) {
            final int threadId = i;
            threads[i] = new Thread(() -> {
                for (int j = 0; j < OPS_PER_THREAD; j++) {
                    String key = "SAV" + (threadId * 1000 + j % 100);
                    map.put(key, new BigDecimal(j));
                    map.get(key);
                }
            });
            threads[i].start();
        }
        for (Thread t : threads) t.join();

        long elapsed = System.currentTimeMillis() - start;
        System.out.println(name + ": " + map.size() + " entries, " + elapsed + " ms");
        return elapsed;
    }
}
TEXT
Expected output:
synchronizedMap: 1000 entries, 487 ms
ConcurrentHashMap: 1000 entries, 142 ms

synchronizedMap: 487 ms
ConcurrentHashMap: 142 ms
ConcurrentHashMap is typically 2-5x faster under contention.

What about CopyOnWriteArrayList?

CopyOnWriteArrayList creates a brand-new copy of the internal array every time you add, set, or remove an element. Reads (get, iterate) work on the current snapshot without locking, making them very fast. Writes are expensive because they copy the entire array.

Use CopyOnWriteArrayList when reads vastly outnumber writes. In a banking application, this is useful for a list of active branches, supported currencies, or interest rate tiers that change rarely but are read on every transaction.

JAVA
package com.bank.atomic;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.List;

public class CopyOnWriteDemo {
    public static void main(String[] args) throws InterruptedException {
        CopyOnWriteArrayList<String> branches = new CopyOnWriteArrayList<>();
        branches.add("Mumbai Main Branch");
        branches.add("Delhi Branch");
        branches.add("Chennai Branch");

        System.out.println("=== CopyOnWriteArrayList ===");
        System.out.println("Initial branches: " + branches);

        // Reader thread: iterates without locking
        Thread reader = new Thread(() -> {
            for (String branch : branches) {
                System.out.println("  [reader] Processing: " + branch);
                try { Thread.sleep(50); } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }, "reader");

        // Writer thread: adds a branch while reader is iterating
        Thread writer = new Thread(() -> {
            try { Thread.sleep(75); } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            branches.add("Bangalore Branch");
            System.out.println("  [writer] Added Bangalore Branch");
        }, "writer");

        reader.start();
        writer.start();
        reader.join();
        writer.join();

        System.out.println();
        System.out.println("Final branches: " + branches);
        System.out.println();
        System.out.println("Key points:");
        System.out.println("  1. Reader saw a consistent snapshot (no ConcurrentModificationException)");
        System.out.println("  2. Writer created a new array copy when adding");
        System.out.println("  3. Use when reads >> writes (branch list, config list)");
        System.out.println("  4. Do NOT use for large lists with frequent writes");
    }
}
TEXT
Expected output:
=== CopyOnWriteArrayList ===
Initial branches: [Mumbai Main Branch, Delhi Branch, Chennai Branch]
  [reader] Processing: Mumbai Main Branch
  [reader] Processing: Delhi Branch
  [writer] Added Bangalore Branch
  [reader] Processing: Chennai Branch

Final branches: [Mumbai Main Branch, Delhi Branch, Chennai Branch, Bangalore Branch]

Key points:
  1. Reader saw a consistent snapshot (no ConcurrentModificationException)
  2. Writer created a new array copy when adding
  3. Use when reads >> writes (branch list, config list)
  4. Do NOT use for large lists with frequent writes

Notice the reader iterated over three branches (the snapshot at the time iteration started), even though the writer added a fourth branch during iteration. No exception occurred.

What are common mistakes with atomic variables and concurrent collections?

Wrong: non-atomic check-then-act with AtomicInteger

JAVA
package com.bank.atomic;

import java.util.concurrent.atomic.AtomicInteger;

public class WrongAtomicCheckThenAct {
    private static final AtomicInteger availableTickets = new AtomicInteger(1);

    public static void main(String[] args) throws InterruptedException {
        System.out.println("WRONG: check-then-act is NOT atomic");
        System.out.println();

        // Two threads try to grab the last loan approval slot
        Runnable grabSlot = () -> {
            // WRONG: get() and decrementAndGet() are separate operations
            // Another thread can sneak in between
            if (availableTickets.get() > 0) {
                // Race condition window: both threads can pass this check
                int remaining = availableTickets.decrementAndGet();
                System.out.println("  [" + Thread.currentThread().getName()
                    + "] Got a slot, remaining: " + remaining);
            } else {
                System.out.println("  [" + Thread.currentThread().getName()
                    + "] No slots available");
            }
        };

        Thread priya = new Thread(grabSlot, "Priya");
        Thread rajesh = new Thread(grabSlot, "Rajesh");
        priya.start();
        rajesh.start();
        priya.join();
        rajesh.join();

        System.out.println("Final slots: " + availableTickets.get());
        System.out.println("  (Could be -1 if both threads passed the check)");
    }
}
TEXT
Expected output:
WRONG: check-then-act is NOT atomic

  [Priya] Got a slot, remaining: 0
  [Rajesh] Got a slot, remaining: -1
Final slots: -1
  (Could be -1 if both threads passed the check)

Correct: use compareAndSet for atomic check-then-act

JAVA
package com.bank.atomic;

import java.util.concurrent.atomic.AtomicInteger;

public class CorrectAtomicCheckThenAct {
    private static final AtomicInteger availableSlots = new AtomicInteger(1);

    public static void main(String[] args) throws InterruptedException {
        System.out.println("CORRECT: use compareAndSet for atomic check-then-act");
        System.out.println();

        Runnable grabSlot = () -> {
            int current;
            do {
                current = availableSlots.get();
                if (current <= 0) {
                    System.out.println("  [" + Thread.currentThread().getName()
                        + "] No slots available");
                    return;
                }
            } while (!availableSlots.compareAndSet(current, current - 1));

            System.out.println("  [" + Thread.currentThread().getName()
                + "] Got a slot, remaining: " + availableSlots.get());
        };

        Thread priya = new Thread(grabSlot, "Priya");
        Thread rajesh = new Thread(grabSlot, "Rajesh");
        priya.start();
        rajesh.start();
        priya.join();
        rajesh.join();

        System.out.println("Final slots: " + availableSlots.get());
        System.out.println("  (Always >= 0, no overselling)");
    }
}
TEXT
Expected output:
CORRECT: use compareAndSet for atomic check-then-act

  [Priya] Got a slot, remaining: 0
  [Rajesh] No slots available
Final slots: 0
  (Always >= 0, no overselling)

Wrong: using ConcurrentHashMap but not atomic compound operations

JAVA
package com.bank.atomic;

import java.util.concurrent.ConcurrentHashMap;

public class WrongConcurrentMapUsage {
    public static void main(String[] args) throws InterruptedException {
        ConcurrentHashMap<String, Integer> loginAttempts = new ConcurrentHashMap<>();
        loginAttempts.put("Rajesh", 0);

        System.out.println("WRONG: get-then-put is not atomic on ConcurrentHashMap");
        System.out.println();

        Runnable incrementLogin = () -> {
            for (int i = 0; i < 1000; i++) {
                // WRONG: get() and put() are separate operations
                int current = loginAttempts.get("Rajesh");
                loginAttempts.put("Rajesh", current + 1);
            }
        };

        Thread t1 = new Thread(incrementLogin);
        Thread t2 = new Thread(incrementLogin);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Login attempts: " + loginAttempts.get("Rajesh"));
        System.out.println("Expected: 2000 (but likely less due to lost updates)");
    }
}
TEXT
Expected output:
WRONG: get-then-put is not atomic on ConcurrentHashMap

Login attempts: 1547
Expected: 2000 (but likely less due to lost updates)

Correct: use merge() for atomic update

JAVA
package com.bank.atomic;

import java.util.concurrent.ConcurrentHashMap;

public class CorrectConcurrentMapUsage {
    public static void main(String[] args) throws InterruptedException {
        ConcurrentHashMap<String, Integer> loginAttempts = new ConcurrentHashMap<>();
        loginAttempts.put("Rajesh", 0);

        System.out.println("CORRECT: use merge() for atomic update");
        System.out.println();

        Runnable incrementLogin = () -> {
            for (int i = 0; i < 1000; i++) {
                // CORRECT: merge is atomic
                loginAttempts.merge("Rajesh", 1, Integer::sum);
            }
        };

        Thread t1 = new Thread(incrementLogin);
        Thread t2 = new Thread(incrementLogin);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Login attempts: " + loginAttempts.get("Rajesh"));
        System.out.println("Expected: 2000 (always correct with merge)");
    }
}
TEXT
Expected output:
CORRECT: use merge() for atomic update

Login attempts: 2000
Expected: 2000 (always correct with merge)

What is a complete banking project using atomic variables and concurrent collections?

This project builds a real-time account balance cache for National Bank of India. Multiple teller threads process deposits and withdrawals concurrently. The system uses AtomicLong for the transaction counter, ConcurrentHashMap for the account cache, and LongAdder for a high-throughput operations counter.

Project structure

DIAGRAM
banking-concurrent-cache/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── com/
                └── bank/
                    ├── model/
                    │   └── AccountCache.java            (concurrent account store)
                    ├── service/
                    │   └── TellerService.java            (teller thread logic)
                    └── ConcurrentCacheApp.java           (main class)

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
    syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>

    syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
    syn-kw"><artifactIdsyn-kw">>banking-concurrent-cachesyn-kw"></artifactIdsyn-kw">>
    syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
    syn-kw"><packagingsyn-kw">>jarsyn-kw"></packagingsyn-kw">>

    syn-kw"><propertiessyn-kw">>
        syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
        syn-kw"><maven.compiler.sourcesyn-kw">>25syn-kw"></maven.compiler.sourcesyn-kw">>
        syn-kw"><maven.compiler.targetsyn-kw">>25syn-kw"></maven.compiler.targetsyn-kw">>
    syn-kw"></propertiessyn-kw">>
syn-kw"></projectsyn-kw">>

AccountCache.java

JAVA
package com.bank.model;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.math.BigDecimal;

public class AccountCache {
    private final ConcurrentHashMap<String, BigDecimal> balances = new ConcurrentHashMap<>();
    private final AtomicLong transactionIdGenerator = new AtomicLong(1000);
    private final LongAdder operationCounter = new LongAdder();

    public void createAccount(String accountId, BigDecimal initialBalance) {
        balances.put(accountId, initialBalance);
    }

    public long deposit(String accountId, BigDecimal amount) {
        long txnId = transactionIdGenerator.incrementAndGet();
        balances.merge(accountId, amount, BigDecimal::add);
        operationCounter.increment();
        return txnId;
    }

    public long withdraw(String accountId, BigDecimal amount) {
        long txnId = transactionIdGenerator.incrementAndGet();
        balances.computeIfPresent(accountId, (key, current) -> {
            if (current.compareTo(amount) >= 0) {
                return current.subtract(amount);
            }
            return current; // Insufficient funds, no change
        });
        operationCounter.increment();
        return txnId;
    }

    public BigDecimal getBalance(String accountId) {
        return balances.getOrDefault(accountId, BigDecimal.ZERO);
    }

    public long getOperationCount() {
        return operationCounter.sum();
    }

    public long getLastTransactionId() {
        return transactionIdGenerator.get();
    }

    public int getAccountCount() {
        return balances.size();
    }
}

TellerService.java

JAVA
package com.bank.service;

import com.bank.model.AccountCache;
import java.math.BigDecimal;

public class TellerService implements Runnable {
    private final AccountCache cache;
    private final String tellerName;
    private final String accountId;
    private final int transactionCount;

    public TellerService(AccountCache cache, String tellerName,
                          String accountId, int transactionCount) {
        this.cache = cache;
        this.tellerName = tellerName;
        this.accountId = accountId;
        this.transactionCount = transactionCount;
    }

    @Override
    public void run() {
        for (int i = 0; i < transactionCount; i++) {
            if (i % 2 == 0) {
                long txnId = cache.deposit(accountId, new BigDecimal("1000.00"));
                System.out.println("  [" + tellerName + "] TXN-" + txnId
                    + " Deposit 1000.00 to " + accountId);
            } else {
                long txnId = cache.withdraw(accountId, new BigDecimal("500.00"));
                System.out.println("  [" + tellerName + "] TXN-" + txnId
                    + " Withdraw 500.00 from " + accountId);
            }
        }
    }
}

ConcurrentCacheApp.java

JAVA
package com.bank;

import com.bank.model.AccountCache;
import com.bank.service.TellerService;
import java.math.BigDecimal;

public class ConcurrentCacheApp {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("National Bank of India - Concurrent Account Cache");
        System.out.println("==================================================");
        System.out.println();

        AccountCache cache = new AccountCache();
        cache.createAccount("SAV2001", new BigDecimal("100000.00"));
        cache.createAccount("SAV2002", new BigDecimal("200000.00"));

        System.out.println("Initial SAV2001: " + cache.getBalance("SAV2001") + " INR");
        System.out.println("Initial SAV2002: " + cache.getBalance("SAV2002") + " INR");
        System.out.println();

        // 3 tellers working on SAV2001, 2 tellers on SAV2002
        Thread teller1 = new Thread(new TellerService(cache, "Teller-Rajesh", "SAV2001", 4));
        Thread teller2 = new Thread(new TellerService(cache, "Teller-Priya", "SAV2001", 4));
        Thread teller3 = new Thread(new TellerService(cache, "Teller-Amit", "SAV2001", 4));
        Thread teller4 = new Thread(new TellerService(cache, "Teller-Neha", "SAV2002", 4));
        Thread teller5 = new Thread(new TellerService(cache, "Teller-Suresh", "SAV2002", 4));

        teller1.start();
        teller2.start();
        teller3.start();
        teller4.start();
        teller5.start();

        teller1.join();
        teller2.join();
        teller3.join();
        teller4.join();
        teller5.join();

        System.out.println();
        System.out.println("=== Final State ===");
        System.out.println("SAV2001 balance:   " + cache.getBalance("SAV2001") + " INR");
        System.out.println("SAV2002 balance:   " + cache.getBalance("SAV2002") + " INR");
        System.out.println("Total operations:  " + cache.getOperationCount());
        System.out.println("Last transaction:  TXN-" + cache.getLastTransactionId());
        System.out.println("Accounts in cache: " + cache.getAccountCount());
        System.out.println();
        System.out.println("SAV2001 expected: 100000 + (6*1000) - (6*500) = 103000.00 INR");
        System.out.println("SAV2002 expected: 200000 + (4*1000) - (4*500) = 202000.00 INR");
    }
}
TEXT
Expected output:
National Bank of India - Concurrent Account Cache
==================================================

Initial SAV2001: 100000.00 INR
Initial SAV2002: 200000.00 INR

  [Teller-Rajesh] TXN-1001 Deposit 1000.00 to SAV2001
  [Teller-Rajesh] TXN-1002 Withdraw 500.00 from SAV2001
  [Teller-Priya] TXN-1003 Deposit 1000.00 to SAV2001
  [Teller-Amit] TXN-1004 Deposit 1000.00 to SAV2001
  [Teller-Neha] TXN-1005 Deposit 1000.00 to SAV2002
  [Teller-Suresh] TXN-1006 Deposit 1000.00 to SAV2002
  [Teller-Priya] TXN-1007 Withdraw 500.00 from SAV2001
  [Teller-Rajesh] TXN-1008 Deposit 1000.00 to SAV2001
  [Teller-Amit] TXN-1009 Withdraw 500.00 from SAV2001
  [Teller-Neha] TXN-1010 Withdraw 500.00 from SAV2002
  [Teller-Suresh] TXN-1011 Withdraw 500.00 from SAV2002
  [Teller-Rajesh] TXN-1012 Withdraw 500.00 from SAV2001
  [Teller-Priya] TXN-1013 Deposit 1000.00 to SAV2001
  [Teller-Amit] TXN-1014 Deposit 1000.00 to SAV2001
  [Teller-Priya] TXN-1015 Withdraw 500.00 from SAV2001
  [Teller-Amit] TXN-1016 Withdraw 500.00 from SAV2001
  [Teller-Neha] TXN-1017 Deposit 1000.00 to SAV2002
  [Teller-Suresh] TXN-1018 Deposit 1000.00 to SAV2002
  [Teller-Neha] TXN-1019 Withdraw 500.00 from SAV2002
  [Teller-Suresh] TXN-1020 Withdraw 500.00 from SAV2002

=== Final State ===
SAV2001 balance:   103000.00 INR
SAV2002 balance:   202000.00 INR
Total operations:  20
Last transaction:  TXN-1020
Accounts in cache: 2

SAV2001 expected: 100000 + (6*1000) - (6*500) = 103000.00 INR
SAV2002 expected: 200000 + (4*1000) - (4*500) = 202000.00 INR

What should a senior or principal engineer know?

At the senior level, you should understand when CAS degrades, how to choose between atomic classes and locks, and how ConcurrentHashMap handles resizing.

  • CAS contention: Under high contention, CAS causes excessive spinning. Each failed CAS retries immediately, wasting CPU cycles. Use LongAdder instead of AtomicLong for counters under high write contention. LongAdder distributes updates across multiple cells and sums them on read.
  • ABA problem: CAS checks if the value is the same, but it cannot detect if the value changed from A to B and back to A. Use AtomicStampedReference to track a version stamp alongside the reference.
  • ConcurrentHashMap internals (Java 8+): The map uses an array of nodes. Each bucket starts as a linked list and converts to a red-black tree when the bucket exceeds 8 entries (TREEIFY_THRESHOLD). Reads use volatile reads without locking. Writes use CAS for the first node in a bucket and synchronized on the node for collisions.
  • ConcurrentHashMap.size() is approximate: Under concurrent modification, size() and mappingCount() return an estimate. For exact counts, you need external synchronization or a separate counter.
  • False sharing: Atomic variables stored next to each other in memory can suffer from false sharing, where different variables on the same CPU cache line invalidate each other. Use @Contended annotation (JDK internal) or manual padding to prevent this.
  • VarHandle (Java 9+): VarHandle provides CAS operations on plain fields without wrapping them in Atomic classes, reducing object overhead.
JAVA
package com.bank.atomic;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class SeniorAtomicKnowledgeDemo {
    public static void main(String[] args) throws InterruptedException {
        int threads = 16;
        int opsPerThread = 1_000_000;

        // AtomicLong under high contention
        AtomicLong atomicCounter = new AtomicLong(0);
        long atomicTime = benchmark(threads, opsPerThread, () -> atomicCounter.incrementAndGet());

        // LongAdder under high contention
        LongAdder adderCounter = new LongAdder();
        long adderTime = benchmark(threads, opsPerThread, adderCounter::increment);

        System.out.println("=== High Contention Benchmark (" + threads + " threads) ===");
        System.out.println("AtomicLong: " + atomicTime + " ms, value = " + atomicCounter.get());
        System.out.println("LongAdder:  " + adderTime + " ms, value = " + adderCounter.sum());
        System.out.println();

        if (adderTime < atomicTime) {
            System.out.println("LongAdder was " + (atomicTime / Math.max(adderTime, 1))
                + "x faster under high contention.");
        }
        System.out.println();

        System.out.println("=== Senior/Principal Checklist ===");
        System.out.println("1. LongAdder > AtomicLong for high-contention counters");
        System.out.println("2. ABA problem: use AtomicStampedReference for versioned CAS");
        System.out.println("3. ConcurrentHashMap: linked list to tree at 8 entries per bucket");
        System.out.println("4. ConcurrentHashMap.size() is approximate under concurrency");
        System.out.println("5. False sharing: @Contended or manual padding for adjacent atomics");
        System.out.println("6. VarHandle (Java 9+): CAS on plain fields without Atomic wrappers");
    }

    private static long benchmark(int threadCount, int opsPerThread, Runnable op)
            throws InterruptedException {
        Thread[] threads = new Thread[threadCount];
        long start = System.currentTimeMillis();
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < opsPerThread; j++) op.run();
            });
            threads[i].start();
        }
        for (Thread t : threads) t.join();
        return System.currentTimeMillis() - start;
    }
}
TEXT
Expected output:
=== High Contention Benchmark (16 threads) ===
AtomicLong: 420 ms, value = 16000000
LongAdder:  85 ms, value = 16000000

LongAdder was 4x faster under high contention.

=== Senior/Principal Checklist ===
1. LongAdder > AtomicLong for high-contention counters
2. ABA problem: use AtomicStampedReference for versioned CAS
3. ConcurrentHashMap: linked list to tree at 8 entries per bucket
4. ConcurrentHashMap.size() is approximate under concurrency
5. False sharing: @Contended or manual padding for adjacent atomics
6. VarHandle (Java 9+): CAS on plain fields without Atomic wrappers

What are common interview follow-up questions?

  • What is the ABA problem? (A value changes from A to B to A. CAS sees A and thinks nothing changed, but the state may be different. Use AtomicStampedReference to detect intermediate changes.)
  • Can you use AtomicReference for a BigDecimal balance? (Yes. Use AtomicReference and compareAndSet or updateAndGet for atomic balance updates without synchronized.)
  • What is the difference between volatile and AtomicInteger? (volatile guarantees visibility but not atomicity of compound operations. count++ on a volatile int is still a race condition. AtomicInteger makes compound operations atomic with CAS.)
  • When should you use ConcurrentHashMap vs synchronized HashMap? (ConcurrentHashMap when multiple threads read and write frequently. synchronizedMap when you need to lock the entire map for multi-step operations like iterating and modifying.)
  • What is LongAdder and when should you use it? (LongAdder distributes increments across cells to reduce CAS contention. Use it for high-throughput counters and metrics. Use AtomicLong when you need the exact current value in real time.)
  • What happens if CAS keeps failing? (The thread spins in a retry loop, consuming CPU. Under extreme contention, this is worse than a lock because all threads spin. The solution is LongAdder or backing off with Thread.onSpinWait().)
  • Can ConcurrentHashMap have null keys or values? (No. Both null keys and null values are prohibited. Use Optional or a sentinel value instead.)

Visual Overview

DIAGRAM
 Compare-and-Swap (CAS) Operation
 ==================================

 Thread A reads value:
 ┌───────────────────┐
 │ Memory: balance=100│
 │ Thread A expected  │
 │   = 100            │
 │ Thread A new       │
 │   = 125            │
 └─────────┬─────────┘
           │ CAS(expected=100, new=125)
           ▼
 ┌───────────────────┐
 │ CPU CAS Instruction│
 │                   │
 │ current == 100?   │
 │   YES: write 125  │
 │   NO:  do nothing │
 └─────────┬─────────┘
           │ success = true
           ▼
 ┌───────────────────┐
 │ Memory: balance=125│
 └───────────────────┘


 CAS Retry (Spin Loop)
 ======================

 Thread A             Thread B
    │                    │
    │ read balance=100   │ read balance=100
    │ new = 125          │ new = 110
    │                    │
    │                    │ CAS(100, 110) -> SUCCESS
    │                    │ balance is now 110
    │                    │
    │ CAS(100, 125)      │
    │   -> FAIL          │
    │   (current=110     │
    │    != expected=100) │
    │                    │
    │ RETRY:             │
    │ read balance=110   │
    │ new = 135          │
    │ CAS(110, 135)      │
    │   -> SUCCESS       │
    │ balance is now 135 │
    │                    │


 ConcurrentHashMap Bucket-Level Locking
 ========================================

 ┌────────────────────────────────────────────┐
 │           ConcurrentHashMap                 │
 │                                            │
 │  Bucket 0    Bucket 1    Bucket 2    ...   │
 │  ┌──────┐   ┌──────┐   ┌──────┐           │
 │  │SAV001│   │SAV002│   │CUR001│           │
 │  │  ▼   │   │  ▼   │   │  ▼   │           │
 │  │SAV005│   │SAV006│   │CUR003│           │
 │  └──────┘   └──────┘   └──────┘           │
 │                                            │
 │  Thread A    Thread B    Thread C          │
 │  writes to   writes to   reads from        │
 │  Bucket 0    Bucket 1    Bucket 2          │
 │  (locked)    (locked)    (no lock needed)  │
 │                                            │
 │  All three threads work simultaneously     │
 │  because they touch different buckets.     │
 └────────────────────────────────────────────┘


 AtomicLong vs LongAdder
 ========================

 AtomicLong (single value):
 ┌────────────┐
 │  value=500 │ <- all threads CAS on this one value
 └────────────┘    high contention = many retries

 LongAdder (multiple cells):
 ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
 │ cell 0 │ │ cell 1 │ │ cell 2 │ │ cell 3 │
 │  =125  │ │  =130  │ │  =120  │ │  =125  │
 └────────┘ └────────┘ └────────┘ └────────┘
   Thread 0   Thread 1   Thread 2   Thread 3
   (no contention: each thread updates its own cell)

 sum() = 125 + 130 + 120 + 125 = 500

Key Takeaway

Atomic variables provide thread-safe operations on single values without using locks. They use compare-and-swap (CAS), a CPU instruction that reads the current value, checks if it matches the expected value, and writes the new value in a single atomic step. If another thread changed the value first, the CAS fails and the code retries. This avoids the overhead of acquiring locks, blocking threads, and context switching, making atomic variables faster than synchronized blocks for simple operations like counters and accumulators.

Concurrent collections extend this idea to data structures. ConcurrentHashMap uses bucket-level locking so that multiple threads can read and write to different parts of the map at the same time. CopyOnWriteArrayList creates a new array copy on every write, making iteration safe without locks. These collections live in java.util.concurrent and should be your default choice when multiple threads access a shared collection.

In our National Bank of India concurrent cache project, we used AtomicLong for generating unique transaction IDs, ConcurrentHashMap for the account balance cache with atomic merge and compute operations, and LongAdder for a high-throughput operations counter. Five teller threads processed deposits and withdrawals concurrently on two accounts without any synchronized blocks. The final balances were always correct because each operation (merge, computeIfPresent) is atomic at the bucket level.

At the senior level, understand when CAS performance degrades. Under high contention (many threads updating the same value), CAS causes excessive spinning that wastes CPU. Use LongAdder for counters with high write throughput. Be aware of the ABA problem and use AtomicStampedReference when intermediate state changes matter. Know that ConcurrentHashMap converts linked-list buckets to red-black trees at 8 entries, that size() is approximate under concurrency, and that null keys and values are not allowed. At the principal level, consider VarHandle for CAS on plain fields without Atomic wrappers, and use @Contended to prevent false sharing between adjacent atomic variables.

Remember one sentence: atomic variables use compare-and-swap to update values without locks, ConcurrentHashMap uses bucket-level locking for concurrent map access, and LongAdder distributes updates across cells to handle high contention.

---

Share
Use ← → arrow keys to navigate