medium.com 15 min read Original Source

Java Concurrency: Each Tool Exists Because the Previous One Was Not Enough

Ten threads each deposit 100 and withdraw 100 simultaneously. The final balance should always be zero. It rarely is.

That is the problem this article solves, progressively. Every fix introduces a new failure mode. Every failure mode motivates the next tool. By the end you will understand not just what each class does but the exact scenario where it beats everything else.

Before the code, one distinction worth keeping in mind throughout:

Blocking algorithms suspend a thread when it cannot proceed. The OS removes it from the run queue until the condition changes. A slow or crashed thread holding a lock stalls every thread waiting for it.

Non-blocking algorithms use CPU-level atomic operations. When a thread cannot proceed, it retries immediately without suspending. The precise guarantee is lock-freedom: the system as a whole always makes progress, even if individual threads spin under high contention. No thread can be permanently blocked by another thread holding a lock.

Every class in this article falls into one of these two families. That is the lens.

The broken counter

public class BankAccount {
    private int balance;
public void deposit(int amount)  { balance += amount; }
    public void withdraw(int amount) { balance -= amount; }
    public int  getBalance()         { return balance; }
}
public class BankAccount {
    private int balance;
public void deposit(int amount)  { balance += amount; }
    public void withdraw(int amount) { balance -= amount; }
    public int  getBalance()         { return balance; }
}

balance += amount looks like one operation. It is three:

1. READ  balance from memory into register
2. ADD   amount to the register value
3. WRITE register back to memory
1. READ  balance from memory into register
2. ADD   amount to the register value
3. WRITE register back to memory

Two threads can both execute step 1 and read the same value before either writes back. Both compute their result from the same starting point. One write overwrites the other. One update disappears silently. This is the lost update problem, in memory rather than in a database.

<button data-code="BankAccount account = new BankAccount();
ExecutorService pool = Executors.newFixedThreadPool(10);

for (int i = 0; i account.deposit(100));
pool.submit(() -> account.withdraw(100));
}
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("Final balance: " + account.getBalance()); // rarely 0″ data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

BankAccount account = new BankAccount();
ExecutorService pool = Executors.newFixedThreadPool(10);

for (int i = 0; i < 1000; i++) {
    pool.submit(() -> account.deposit(100));
    pool.submit(() -> account.withdraw(100));
}
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("Final balance: " + account.getBalance()); // rarely 0
BankAccount account = new BankAccount();
ExecutorService pool = Executors.newFixedThreadPool(10);

for (int i = 0; i < 1000; i++) {
    pool.submit(() -> account.deposit(100));
    pool.submit(() -> account.withdraw(100));
}
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("Final balance: " + account.getBalance()); // rarely 0

synchronized: the obvious fix and its four problems

public synchronized void deposit(int amount)  { balance += amount; }
public synchronized void withdraw(int amount) { balance -= amount; }
public synchronized int  getBalance()         { return balance; }
public synchronized void deposit(int amount)  { balance += amount; }
public synchronized void withdraw(int amount) { balance -= amount; }
public synchronized int  getBalance()         { return balance; }

synchronized acquires the object’s intrinsic lock. Only one thread holds it at a time. Others block at the method entry until it is released. The counter is fixed.

Four problems remain.

Readers block readers. Ten threads calling getBalance() queue up one at a time even though concurrent reads are perfectly safe. Reads are serialized unnecessarily.

No timeout. If a thread holds the lock for a long time, every other thread waits indefinitely. There is no way to say “try for 500ms then give up”.

No backout. Once a thread is blocked waiting for a lock, it cannot change its mind. It will wait forever. This makes certain deadlock scenarios unresolvable.

No fairness. There is no guarantee about which waiting thread gets the lock when it is released. A thread that has waited 10 seconds can be skipped repeatedly by threads that just arrived.

ReentrantLock: explicit control over all four

ReentrantLock gives the same mutual exclusion as synchronized plus solutions to all four problems above.

import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
    private int balance;
    private final ReentrantLock lock = new ReentrantLock();
    public void deposit(int amount) {
        lock.lock();
        try {
            balance += amount;
        } finally {
            lock.unlock(); // always in finally, if you forget, the lock is held forever
        }
    }
}
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
    private int balance;
    private final ReentrantLock lock = new ReentrantLock();
    public void deposit(int amount) {
        lock.lock();
        try {
            balance += amount;
        } finally {
            lock.unlock(); // always in finally, if you forget, the lock is held forever
        }
    }
}

The finally block is not optional. synchronized releases the lock automatically on exception. ReentrantLock does not. Forgetting finally means the lock is held forever and every subsequent caller blocks indefinitely.

tryLock: the deadlock escape hatch

The classic deadlock with synchronized:

Thread A holds Lock 1, needs Lock 2
Thread B holds Lock 2, needs Lock 1
Both blocked forever, no way out
Thread A holds Lock 1, needs Lock 2
Thread B holds Lock 2, needs Lock 1
Both blocked forever, no way out

With tryLock:

public boolean transfer(ReentrantLock fromLock, ReentrantLock toLock,
                        BankAccount from, BankAccount to, int amount) {
    boolean acquiredFrom = false;
    boolean acquiredTo   = false;
try {
        acquiredFrom = fromLock.tryLock(50, TimeUnit.MILLISECONDS);
        acquiredTo   = toLock.tryLock(50, TimeUnit.MILLISECONDS);
        if (acquiredFrom && acquiredTo) {
            from.withdraw(amount);
            to.deposit(amount);
            return true;
        }
        return false; // back out, caller retries
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return false;
    } finally {
        if (acquiredFrom) fromLock.unlock();
        if (acquiredTo)   toLock.unlock();
    }
}
public boolean transfer(ReentrantLock fromLock, ReentrantLock toLock,
                        BankAccount from, BankAccount to, int amount) {
    boolean acquiredFrom = false;
    boolean acquiredTo   = false;
try {
        acquiredFrom = fromLock.tryLock(50, TimeUnit.MILLISECONDS);
        acquiredTo   = toLock.tryLock(50, TimeUnit.MILLISECONDS);
        if (acquiredFrom && acquiredTo) {
            from.withdraw(amount);
            to.deposit(amount);
            return true;
        }
        return false; // back out, caller retries
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return false;
    } finally {
        if (acquiredFrom) fromLock.unlock();
        if (acquiredTo)   toLock.unlock();
    }
}

If both locks cannot be acquired within 50ms, both are released and the transfer fails cleanly. With synchronized, the thread blocks forever.

Fair mode:

ReentrantLock fairLock = new ReentrantLock(true);
// threads acquire the lock in the order they started waiting
ReentrantLock fairLock = new ReentrantLock(true);
// threads acquire the lock in the order they started waiting

synchronized has no fairness guarantee. ReentrantLock(true) queues threads in arrival order, preventing starvation at the cost of some throughput.

ReentrantReadWriteLock: reads should not block reads

ReentrantLock serializes everything, including concurrent reads that are perfectly safe. ReentrantReadWriteLock maintains two locks: a read lock that multiple threads can hold simultaneously, and a write lock that requires exclusive access.

import java.util.concurrent.locks.ReentrantReadWriteLock;
public class BankAccount {
    private int balance;
    private final ReentrantReadWriteLock rwLock   = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.ReadLock  readLock  = rwLock.readLock();
    private final ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
    public void deposit(int amount) {
        writeLock.lock();
        try { balance += amount; }
        finally { writeLock.unlock(); }
    }
    public int getBalance() {
        readLock.lock();
        try { return balance; }
        finally { readLock.unlock(); }
    }
}
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class BankAccount {
    private int balance;
    private final ReentrantReadWriteLock rwLock   = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.ReadLock  readLock  = rwLock.readLock();
    private final ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
    public void deposit(int amount) {
        writeLock.lock();
        try { balance += amount; }
        finally { writeLock.unlock(); }
    }
    public int getBalance() {
        readLock.lock();
        try { return balance; }
        finally { readLock.unlock(); }
    }
}

With ReentrantLock, ten concurrent reads queue one at a time. With ReentrantReadWriteLock, all ten read simultaneously. The throughput difference is proportional to the number of concurrent readers.

The limitation: write starvation is possible under a constant stream of readers. The writer keeps being blocked. Fair mode (new ReentrantReadWriteLock(true)) prevents this.

StampedLock: optimistic reads without acquiring a lock at all

ReentrantReadWriteLock still requires acquiring the read lock on every read. Under very high read contention, even that synchronization accumulates cost.

StampedLock adds a third mode: optimistic read. Read the data without acquiring any lock. Then validate. If no write happened during the read, the data is consistent. If a write happened, fall back to a real read lock.

import java.util.concurrent.locks.StampedLock;
public class BankAccount {
    private int balance;
    private final StampedLock lock = new StampedLock();
    public void deposit(int amount) {
        long stamp = lock.writeLock();
        try { balance += amount; }
        finally { lock.unlockWrite(stamp); }
    }
    public int getBalance() {
        long stamp = lock.tryOptimisticRead();
        int  value = balance;
        if (!lock.validate(stamp)) {
            // a write happened during our read, fall back to read lock
            stamp = lock.readLock();
            try { value = balance; }
            finally { lock.unlockRead(stamp); }
        }
        return value;
    }
}
import java.util.concurrent.locks.StampedLock;
public class BankAccount {
    private int balance;
    private final StampedLock lock = new StampedLock();
    public void deposit(int amount) {
        long stamp = lock.writeLock();
        try { balance += amount; }
        finally { lock.unlockWrite(stamp); }
    }
    public int getBalance() {
        long stamp = lock.tryOptimisticRead();
        int  value = balance;
        if (!lock.validate(stamp)) {
            // a write happened during our read, fall back to read lock
            stamp = lock.readLock();
            try { value = balance; }
            finally { lock.unlockRead(stamp); }
        }
        return value;
    }
}

tryOptimisticRead() returns a stamp without acquiring any lock. validate(stamp) checks whether the write lock has been acquired since the stamp was issued. Under read-heavy workloads with rare writes, most reads complete without any synchronization at all.

The caveat worth knowing: StampedLock is not reentrant. A thread holding a write stamp cannot acquire another lock from the same StampedLock. ReentrantLock and ReentrantReadWriteLock allow a thread to acquire the same lock multiple times. StampedLock does not. Using it incorrectly causes a deadlock that is very hard to debug.

In practice, reach for ReentrantReadWriteLock first. Move to StampedLock only if you have benchmarks showing that read-lock acquisition overhead is genuinely a bottleneck. The optimistic read path is powerful but easy to misuse, and the non-reentrant nature has caught out experienced engineers.

AtomicInteger: CAS at the CPU level

All the lock-based solutions above are blocking. A thread waiting for a lock sits idle. For simple operations on a single variable, there is a better way.

Modern CPUs provide compare-and-swap (CAS): in one uninterruptible CPU operation, check whether a memory location contains an expected value and, if so, replace it with a new value. Either the whole thing succeeds or nothing changes.

import java.util.concurrent.atomic.AtomicInteger;
public class BankAccount {
    private final AtomicInteger balance = new AtomicInteger(0);
    public void deposit(int amount)  { balance.addAndGet(amount); }
    public void withdraw(int amount) { balance.addAndGet(-amount); }
    public int  getBalance()         { return balance.get(); }
}
import java.util.concurrent.atomic.AtomicInteger;
public class BankAccount {
    private final AtomicInteger balance = new AtomicInteger(0);
    public void deposit(int amount)  { balance.addAndGet(amount); }
    public void withdraw(int amount) { balance.addAndGet(-amount); }
    public int  getBalance()         { return balance.get(); }
}

addAndGet is implemented as a CAS loop:

public int addAndGet(int delta) {
    while (true) {
        int current = get();
        int next    = current + delta;
        if (compareAndSet(current, next)) return next;
        // CAS failed: another thread changed the value between read and write
        // loop and retry immediately, no suspension
    }
}
public int addAndGet(int delta) {
    while (true) {
        int current = get();
        int next    = current + delta;
        if (compareAndSet(current, next)) return next;
        // CAS failed: another thread changed the value between read and write
        // loop and retry immediately, no suspension
    }
}

No lock. No blocking. The thread spins briefly under contention but never suspends. This is a lock-free algorithm: the system always makes forward progress because at least one thread will always succeed on each CAS attempt, even if others are retrying. Under extreme contention with many threads, individual threads can spin many times before succeeding, but no thread is ever suspended waiting for another to release anything.

The ABA problem

CAS checks whether the value equals the expected value. But “equals expected” is not the same as “nothing changed”.

Thread A reads 100. Thread B changes 100 to 80, then back to 100. Thread A’s CAS compares against 100, succeeds, and thinks nothing happened. Something did.

AtomicStampedReference solves this by pairing the value with a version stamp:

<button data-code="AtomicStampedReference ref = new AtomicStampedReference(100, 0);
int[] stamp = new int[1];
int current = ref.get(stamp);
// CAS only succeeds if both value AND stamp match
ref.compareAndSet(current, newValue, stamp[0], stamp[0] + 1);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

AtomicStampedReference<Integer> ref = new AtomicStampedReference<>(100, 0);
int[] stamp = new int[1];
int current = ref.get(stamp);
// CAS only succeeds if both value AND stamp match
ref.compareAndSet(current, newValue, stamp[0], stamp[0] + 1);
AtomicStampedReference<Integer> ref = new AtomicStampedReference<>(100, 0);
int[] stamp = new int[1];
int current = ref.get(stamp);
// CAS only succeeds if both value AND stamp match
ref.compareAndSet(current, newValue, stamp[0], stamp[0] + 1);

Even if the value returns to 100, the stamp has incremented. The stale CAS fails correctly.

LongAdder vs AtomicLong: when CAS itself becomes the bottleneck

AtomicLong uses a single CAS loop. Under high contention, many threads attempt CAS simultaneously. Most fail and retry. Under extreme contention, threads spend more time retrying than doing actual work.

LongAdder solves this with striping. Instead of one shared counter, it maintains an array of cells. Threads hash to different cells and increment their local cell. The total is the sum of all cells.

import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.atomic.AtomicLong;
AtomicLong  atomicCounter = new AtomicLong(0);
LongAdder   adderCounter  = new LongAdder();
// Under low contention: similar performance
// Under high contention (16+ threads on the same counter):
// LongAdder is 3-10x faster depending on thread count
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.atomic.AtomicLong;
AtomicLong  atomicCounter = new AtomicLong(0);
LongAdder   adderCounter  = new LongAdder();
// Under low contention: similar performance
// Under high contention (16+ threads on the same counter):
// LongAdder is 3-10x faster depending on thread count

The difference in practice:

AtomicLong with 8 threads:
  Thread 1: CAS(0 → 1) succeeds
  Thread 2: reads stale 0, CAS fails, retries, CAS(1 → 2) succeeds
  Thread 3: multiple retries before succeeding
  Many CAS collisions under high contention
LongAdder with 8 threads:
  Threads 1-4: increment cell[0]  (CAS contention only within this group)
  Threads 5-8: increment cell[1]  (separate cell, no conflict with group 1)
  sum(): cell[0] + cell[1]
  Far fewer CAS collisions overall
AtomicLong with 8 threads:
  Thread 1: CAS(0 → 1) succeeds
  Thread 2: reads stale 0, CAS fails, retries, CAS(1 → 2) succeeds
  Thread 3: multiple retries before succeeding
  Many CAS collisions under high contention
LongAdder with 8 threads:
  Threads 1-4: increment cell[0]  (CAS contention only within this group)
  Threads 5-8: increment cell[1]  (separate cell, no conflict with group 1)
  sum(): cell[0] + cell[1]
  Far fewer CAS collisions overall

LongAdder still uses CAS internally on each cell. What it eliminates is the contention between all threads competing for a single memory location. Each cell has its own CAS, so collisions only happen within a cell’s small group of threads, not across all of them.

The trade-off: sum() on LongAdder is not atomic. Other threads can modify cells during the summation. The result is a valid approximate value, not a point-in-time snapshot. Use AtomicLong when you need exact compare-and-swap operations. Use LongAdder for high-throughput counters where approximate totals are acceptable, like request counts or metric aggregation.

ConcurrentHashMap: why HashMap breaks and how CHM fixes it

Most documentation says “HashMap is not thread safe, use ConcurrentHashMap.” That is accurate but not useful. What actually happens to a HashMap under concurrency is worth knowing.

In Java 6 and 7, concurrent HashMap puts caused infinite loops.

HashMap uses an array of linked list buckets. When the load factor is exceeded, it resizes by creating a new array and rehashing all entries. The rehash reverses entry order in each bucket. Under concurrent access, two threads can simultaneously resize the same bucket and create a circular reference in the linked list. Any subsequent get() that traverses that bucket loops forever, pinning a thread at 100% CPU.

<button data-code="// Java 6/7: this could cause a thread to spin forever
Map map = new HashMap();
ExecutorService pool = Executors.newFixedThreadPool(8);
for (int i = 0; i map.put("key" + key, key));
}
// some thread may now be in an infinite loop inside get()” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// Java 6/7: this could cause a thread to spin forever
Map<String, Integer> map = new HashMap<>();
ExecutorService pool = Executors.newFixedThreadPool(8);
for (int i = 0; i < 10000; i++) {
    final int key = i;
    pool.submit(() -> map.put("key" + key, key));
}
// some thread may now be in an infinite loop inside get()
// Java 6/7: this could cause a thread to spin forever
Map<String, Integer> map = new HashMap<>();
ExecutorService pool = Executors.newFixedThreadPool(8);
for (int i = 0; i < 10000; i++) {
    final int key = i;
    pool.submit(() -> map.put("key" + key, key));
}
// some thread may now be in an infinite loop inside get()

Java 8 fixed the infinite loop by switching to a balanced tree (red-black tree) for large buckets and changing the rehash algorithm to preserve entry order. Circular references cannot form. But HashMap is still not thread safe, writes can still corrupt the structure.

ConcurrentHashMap in Java 7 used segment locking: 16 segments each with its own lock. Operations on different segments ran concurrently.

ConcurrentHashMap in Java 8 replaced this entirely: a volatile array of bin heads, CAS for inserts into empty bins, synchronized on the bin head node for operations modifying an existing bin. The result is lock-free reads, CAS-based inserts into empty buckets, and synchronization only when two threads touch the same bucket.

<button data-code="ConcurrentHashMap map = new ConcurrentHashMap();

map.put("alice", 1000);
map.get("alice"); // never blocks
map.putIfAbsent("bob", 500); // atomic check-then-set
map.computeIfAbsent("charlie", k -> loadFromDatabase(k)); // atomic compute-if-missing
map.compute("alice", (k, v) -> v == null ? 100 : v + 100); // atomic read-modify-write
map.merge("alice", 50, Integer::sum); // atomic merge” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

map.put("alice", 1000);
map.get("alice");                                           // never blocks
map.putIfAbsent("bob", 500);                               // atomic check-then-set
map.computeIfAbsent("charlie", k -> loadFromDatabase(k));  // atomic compute-if-missing
map.compute("alice", (k, v) -> v == null ? 100 : v + 100); // atomic read-modify-write
map.merge("alice", 50, Integer::sum);                      // atomic merge
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

map.put("alice", 1000);
map.get("alice");                                           // never blocks
map.putIfAbsent("bob", 500);                               // atomic check-then-set
map.computeIfAbsent("charlie", k -> loadFromDatabase(k));  // atomic compute-if-missing
map.compute("alice", (k, v) -> v == null ? 100 : v + 100); // atomic read-modify-write
map.merge("alice", 50, Integer::sum);                      // atomic merge

compute and merge are atomic. The entire read-check-write happens as a single operation. This eliminates the classic race condition:

loadFromDatabase(k));” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// BROKEN: two threads can both pass the check before either writes
if (!map.containsKey("alice")) {
    map.put("alice", 1000);
}
// CORRECT
map.putIfAbsent("alice", 1000);
map.computeIfAbsent("alice", k -> loadFromDatabase(k));
// BROKEN: two threads can both pass the check before either writes
if (!map.containsKey("alice")) {
    map.put("alice", 1000);
}
// CORRECT
map.putIfAbsent("alice", 1000);
map.computeIfAbsent("alice", k -> loadFromDatabase(k));

One important limitation: size() is approximate under concurrent modification. ConcurrentHashMap uses a LongAdder-style counter internally. The sum at any moment may not reflect every in-flight operation. Use mappingCount() for large maps, it returns long and is designed for this use case.

CopyOnWriteArrayList: reads for free, writes that cost

CopyOnWriteArrayList handles concurrent list access by copying the entire underlying array on every write. Reads require no synchronization because the array being iterated is immutable for the duration of the iteration.

<button data-code="CopyOnWriteArrayList list = new CopyOnWriteArrayList();
list.add("alice");
// any number of threads can iterate simultaneously, no locking
for (String name : list) {
System.out.println(name); // iterating a snapshot, not the live list
}
// writes are expensive
list.add("bob"); // creates a new array of size n+1
list.remove(0); // creates a new array of size n-1″ data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("alice");
// any number of threads can iterate simultaneously, no locking
for (String name : list) {
    System.out.println(name); // iterating a snapshot, not the live list
}
// writes are expensive
list.add("bob");    // creates a new array of size n+1
list.remove(0);     // creates a new array of size n-1
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("alice");
// any number of threads can iterate simultaneously, no locking
for (String name : list) {
    System.out.println(name); // iterating a snapshot, not the live list
}
// writes are expensive
list.add("bob");    // creates a new array of size n+1
list.remove(0);     // creates a new array of size n-1

When it wins: the list is read far more often than written. Event listener lists are the canonical example: registered once at startup, iterated thousands of times per second. Every read is lock-free. The occasional write costs one array copy.

When it loses badly: frequent writes on a large list. Every add() copies the entire array. On a list with 100,000 elements, every write allocates and copies 100,000 elements. Ten writes per second means 1,000,000 element copies per second. The GC pressure alone can destabilize the application.

The rule: CopyOnWriteArrayList is correct when writes are rare and the list is small. For any workload with significant write frequency, use ConcurrentLinkedQueue or a synchronized collection instead.

Blocking queues: the producer-consumer pattern done right

Blocking queues coordinate producers and consumers without manual synchronization. put() blocks if the queue is full. take() blocks if the queue is empty.

<button data-code="BlockingQueue queue = new LinkedBlockingQueue(100);
void produce() throws InterruptedException {
while (running) {
queue.put(generateTask()); // blocks if queue is at 100 capacity
}
}
void consume() throws InterruptedException {
while (running) {
process(queue.take()); // blocks if queue is empty
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

BlockingQueue<Task> queue = new LinkedBlockingQueue<>(100);
void produce() throws InterruptedException {
    while (running) {
        queue.put(generateTask()); // blocks if queue is at 100 capacity
    }
}
void consume() throws InterruptedException {
    while (running) {
        process(queue.take()); // blocks if queue is empty
    }
}
BlockingQueue<Task> queue = new LinkedBlockingQueue<>(100);
void produce() throws InterruptedException {
    while (running) {
        queue.put(generateTask()); // blocks if queue is at 100 capacity
    }
}
void consume() throws InterruptedException {
    while (running) {
        process(queue.take()); // blocks if queue is empty
    }
}

LinkedBlockingQueue uses two locks, one for the head (takes) and one for the tail (puts). Producers and consumers operate simultaneously without blocking each other as long as the queue is neither full nor empty. This is why LinkedBlockingQueue has higher throughput than ArrayBlockingQueue under many concurrent producers and consumers.

ArrayBlockingQueue uses one lock for all operations. Producers and consumers contend with each other. The trade-off is bounded capacity with lower memory overhead. ArrayBlockingQueue pre-allocates its backing array. LinkedBlockingQueue allocates a node per element. At very high throughput, that allocation difference matters.

SynchronousQueue has no storage. Every put() blocks until a thread calls take(). It is a direct handoff mechanism. Used inside Executors.newCachedThreadPool() to transfer tasks directly from caller to thread without buffering.

<button data-code="SynchronousQueue handoff = new SynchronousQueue();
// Thread A hands off directly to Thread B
handoff.put(task); // blocks until B is ready
Task received = handoff.take(); // blocks until A hands off” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

SynchronousQueue<Task> handoff = new SynchronousQueue<>();
// Thread A hands off directly to Thread B
handoff.put(task);            // blocks until B is ready
Task received = handoff.take(); // blocks until A hands off
SynchronousQueue<Task> handoff = new SynchronousQueue<>();
// Thread A hands off directly to Thread B
handoff.put(task);            // blocks until B is ready
Task received = handoff.take(); // blocks until A hands off

DelayQueue for scheduled work. Elements become available only after their delay expires.

<button data-code="class ScheduledTask implements Delayed {
private final long executeAt;
ScheduledTask(long delayMs) {
this.executeAt = System.currentTimeMillis() + delayMs;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(executeAt – System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed other) {
return Long.compare(getDelay(TimeUnit.MILLISECONDS), other.getDelay(TimeUnit.MILLISECONDS));
}
}
DelayQueue scheduler = new DelayQueue();
scheduler.put(new ScheduledTask(5000)); // available in 5 seconds
ScheduledTask task = scheduler.take(); // blocks for 5 seconds then returns” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

class ScheduledTask implements Delayed {
    private final long executeAt;
ScheduledTask(long delayMs) {
        this.executeAt = System.currentTimeMillis() + delayMs;
    }
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(executeAt - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }
    @Override
    public int compareTo(Delayed other) {
        return Long.compare(getDelay(TimeUnit.MILLISECONDS), other.getDelay(TimeUnit.MILLISECONDS));
    }
}
DelayQueue<ScheduledTask> scheduler = new DelayQueue<>();
scheduler.put(new ScheduledTask(5000)); // available in 5 seconds
ScheduledTask task = scheduler.take();  // blocks for 5 seconds then returns
class ScheduledTask implements Delayed {
    private final long executeAt;
ScheduledTask(long delayMs) {
        this.executeAt = System.currentTimeMillis() + delayMs;
    }
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(executeAt - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }
    @Override
    public int compareTo(Delayed other) {
        return Long.compare(getDelay(TimeUnit.MILLISECONDS), other.getDelay(TimeUnit.MILLISECONDS));
    }
}
DelayQueue<ScheduledTask> scheduler = new DelayQueue<>();
scheduler.put(new ScheduledTask(5000)); // available in 5 seconds
ScheduledTask task = scheduler.take();  // blocks for 5 seconds then returns

CountDownLatch, CyclicBarrier, and Phaser

These three sound similar and are not interchangeable. Each solves a problem the other two handle awkwardly.

CountDownLatch: wait for N external events

{ startPaymentService(); ready.countDown(); }).start();
new Thread(() -> { startInventoryService(); ready.countDown(); }).start();
new Thread(() -> { startOrderService(); ready.countDown(); }).start();
ready.await(); // blocks until count reaches 0
System.out.println("All services ready");” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

CountDownLatch ready = new CountDownLatch(3);
new Thread(() -> { startPaymentService();   ready.countDown(); }).start();
new Thread(() -> { startInventoryService(); ready.countDown(); }).start();
new Thread(() -> { startOrderService();     ready.countDown(); }).start();
ready.await(); // blocks until count reaches 0
System.out.println("All services ready");
CountDownLatch ready = new CountDownLatch(3);
new Thread(() -> { startPaymentService();   ready.countDown(); }).start();
new Thread(() -> { startInventoryService(); ready.countDown(); }).start();
new Thread(() -> { startOrderService();     ready.countDown(); }).start();
ready.await(); // blocks until count reaches 0
System.out.println("All services ready");

The count goes only down. Once it reaches zero it stays there. It is a one-shot gate. You cannot reset it.

CyclicBarrier: N threads wait for each other

System.out.println("All threads reached barrier, starting next phase")
);

for (int i = 0; i {
doPhaseOneWork();
barrier.await(); // all 4 must arrive before any continues
doPhaseTwoWork();
barrier.await(); // cyclic: resets automatically for phase 3
doPhaseThreeWork();
}).start();
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

CyclicBarrier barrier = new CyclicBarrier(4, () ->
    System.out.println("All threads reached barrier, starting next phase")
);

for (int i = 0; i < 4; i++) {
    new Thread(() -> {
        doPhaseOneWork();
        barrier.await(); // all 4 must arrive before any continues
        doPhaseTwoWork();
        barrier.await(); // cyclic: resets automatically for phase 3
        doPhaseThreeWork();
    }).start();
}
CyclicBarrier barrier = new CyclicBarrier(4, () ->
    System.out.println("All threads reached barrier, starting next phase")
);

for (int i = 0; i < 4; i++) {
    new Thread(() -> {
        doPhaseOneWork();
        barrier.await(); // all 4 must arrive before any continues
        doPhaseTwoWork();
        barrier.await(); // cyclic: resets automatically for phase 3
        doPhaseThreeWork();
    }).start();
}

The key differences from CountDownLatch: symmetric (all threads wait for each other, not for external events), cyclic (resets after all threads arrive, reusable), and supports a barrier action that runs when all threads arrive before any is released.

Phaser: dynamic participant count

CountDownLatch requires knowing the count at construction. CyclicBarrier requires knowing the thread count. Phaser supports threads registering and deregistering dynamically.

<button data-code="Phaser phaser = new Phaser(1); // register main thread
for (int i = 0; i {
doWork();
phaser.arriveAndDeregister(); // deregister when done
}).start();
}
phaser.arriveAndAwaitAdvance(); // main thread waits for all workers
System.out.println("All workers done");” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

Phaser phaser = new Phaser(1); // register main thread
for (int i = 0; i < 5; i++) {
    phaser.register();
    new Thread(() -> {
        doWork();
        phaser.arriveAndDeregister(); // deregister when done
    }).start();
}
phaser.arriveAndAwaitAdvance(); // main thread waits for all workers
System.out.println("All workers done");
Phaser phaser = new Phaser(1); // register main thread
for (int i = 0; i < 5; i++) {
    phaser.register();
    new Thread(() -> {
        doWork();
        phaser.arriveAndDeregister(); // deregister when done
    }).start();
}
phaser.arriveAndAwaitAdvance(); // main thread waits for all workers
System.out.println("All workers done");

Use CountDownLatch when waiting for a fixed number of external events (one-shot). Use CyclicBarrier when a fixed set of threads synchronize repeatedly at checkpoints. Use Phaser when participants join and leave dynamically.

Semaphore: permits for bounded resource access

A semaphore maintains a count of available permits. acquire() takes a permit and blocks if none are available. release() returns one.

Semaphore connectionPool = new Semaphore(10);
public Result queryDatabase(String sql) throws InterruptedException {
    connectionPool.acquire(); // blocks if 10 connections already in use
    try {
        return executeQuery(sql);
    } finally {
        connectionPool.release();
    }
}
Semaphore connectionPool = new Semaphore(10);
public Result queryDatabase(String sql) throws InterruptedException {
    connectionPool.acquire(); // blocks if 10 connections already in use
    try {
        return executeQuery(sql);
    } finally {
        connectionPool.release();
    }
}

tryAcquire() for non-blocking rate limiting:

if (semaphore.tryAcquire()) {
    try {
        return processRequest();
    } finally {
        semaphore.release();
    }
} else {
    return Response.tooManyRequests();
}
if (semaphore.tryAcquire()) {
    try {
        return processRequest();
    } finally {
        semaphore.release();
    }
} else {
    return Response.tooManyRequests();
}

Fair vs unfair mode matters under load. Fair mode (new Semaphore(10, true)) queues threads in FIFO order, preventing starvation. Unfair mode (the default) allows barging, which is faster under high contention because a thread already running can grab a released permit without a context switch.

Exchanger: two threads swap objects

Exchanger is the most specialised class in the library. Two threads each call exchange(). Both block until the other also calls it. Then they swap values and both continue.

<button data-code="Exchanger<List> exchanger = new Exchanger();

// Thread 1: fills a buffer, exchanges it for an empty one
Thread filler = new Thread(() -> {
List buffer = new ArrayList();
while (running) {
fillBuffer(buffer);
buffer = exchanger.exchange(buffer); // hands off full, gets empty
buffer.clear();
}
});
// Thread 2: processes the full buffer, returns it empty
Thread processor = new Thread(() -> {
List buffer = new ArrayList();
while (running) {
buffer = exchanger.exchange(buffer); // hands off empty, gets full
processBuffer(buffer);
}
});” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

Exchanger<List<Integer>> exchanger = new Exchanger<>();

// Thread 1: fills a buffer, exchanges it for an empty one
Thread filler = new Thread(() -> {
    List<Integer> buffer = new ArrayList<>();
    while (running) {
        fillBuffer(buffer);
        buffer = exchanger.exchange(buffer); // hands off full, gets empty
        buffer.clear();
    }
});
// Thread 2: processes the full buffer, returns it empty
Thread processor = new Thread(() -> {
    List<Integer> buffer = new ArrayList<>();
    while (running) {
        buffer = exchanger.exchange(buffer); // hands off empty, gets full
        processBuffer(buffer);
    }
});
Exchanger<List<Integer>> exchanger = new Exchanger<>();

// Thread 1: fills a buffer, exchanges it for an empty one
Thread filler = new Thread(() -> {
    List<Integer> buffer = new ArrayList<>();
    while (running) {
        fillBuffer(buffer);
        buffer = exchanger.exchange(buffer); // hands off full, gets empty
        buffer.clear();
    }
});
// Thread 2: processes the full buffer, returns it empty
Thread processor = new Thread(() -> {
    List<Integer> buffer = new ArrayList<>();
    while (running) {
        buffer = exchanger.exchange(buffer); // hands off empty, gets full
        processBuffer(buffer);
    }
});

This is the double-buffer pipeline pattern. One thread fills while the other processes. They swap at the exchange point. No copying, no shared state, no locking. The synchronization is the swap itself.

Blocking vs non-blocking: the full picture

Blocking, Thread A is slow:
  T0: Thread A acquires lock
  T1: Thread B arrives, blocks
  T2: Thread C arrives, blocks
  T3-T4: Thread A is slow, B and C wait
  T5: Thread A releases lock
  T6: Thread B proceeds
  Thread B waited the entire duration of A's slowness.
Lock-free (CAS), Thread A is slow:
  T0: Thread A reads value, prepares CAS
  T1: Thread B reads value, prepares CAS
  T2: Thread B's CAS succeeds
  T3: Thread A's CAS fails (B changed the value)
  T4: Thread A retries immediately, succeeds
  Thread B never waited for Thread A at all.
Blocking, Thread A is slow:
  T0: Thread A acquires lock
  T1: Thread B arrives, blocks
  T2: Thread C arrives, blocks
  T3-T4: Thread A is slow, B and C wait
  T5: Thread A releases lock
  T6: Thread B proceeds
  Thread B waited the entire duration of A's slowness.
Lock-free (CAS), Thread A is slow:
  T0: Thread A reads value, prepares CAS
  T1: Thread B reads value, prepares CAS
  T2: Thread B's CAS succeeds
  T3: Thread A's CAS fails (B changed the value)
  T4: Thread A retries immediately, succeeds
  Thread B never waited for Thread A at all.

A precise note on terminology: lock-free guarantees that the system as a whole always makes progress. It does not guarantee that every individual thread makes progress quickly. Under extreme contention, a thread can spin through many failed CAS attempts before succeeding. What it cannot do is be suspended indefinitely by another thread holding a lock.

Use lock-free structures (AtomicLong, LongAdder, ConcurrentLinkedQueue, ConcurrentSkipListMap) for high-contention single values and non-blocking queues.

ConcurrentHashMap is not fully lock-free. It uses CAS for inserts into empty buckets, but falls back to synchronized on the bin head for modifications to existing buckets. The accurate term is highly concurrent, not non-blocking. It fits neither family cleanly, which is why it deserves its own mental category.

Use blocking structures (ReentrantLock, ReentrantReadWriteLock, blocking queues, Semaphore) when coordinating multiple steps, waiting for conditions, or limiting access to a resource with complex state.

ConcurrentLinkedQueue: the canonical lock-free collection

Blocking queues coordinate through locks and condition variables. If the queue is empty, take() suspends the thread. If it is full, put() suspends the thread. That suspension is cheap under normal conditions but adds latency when threads are frequently blocked and unblocked.

ConcurrentLinkedQueue is unbounded and lock-free. It uses CAS on the head and tail pointers. poll() never blocks: it returns null if the queue is empty. offer() never blocks: it always succeeds.

<button data-code="ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();
// Producer: never blocks
queue.offer(new Task());
// Consumer: returns null if empty, never blocks
Task task = queue.poll();
if (task != null) {
process(task);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

ConcurrentLinkedQueue<Task> queue = new ConcurrentLinkedQueue<>();
// Producer: never blocks
queue.offer(new Task());
// Consumer: returns null if empty, never blocks
Task task = queue.poll();
if (task != null) {
    process(task);
}
ConcurrentLinkedQueue<Task> queue = new ConcurrentLinkedQueue<>();
// Producer: never blocks
queue.offer(new Task());
// Consumer: returns null if empty, never blocks
Task task = queue.poll();
if (task != null) {
    process(task);
}

Use ConcurrentLinkedQueue when you want a shared work queue with no backpressure and no blocking. The consumer is responsible for checking whether the queue is empty. Use LinkedBlockingQueue when you want consumers to wait automatically for work to arrive and producers to slow down when the queue is full.

Which tool for which problem

Problem Tool Simple counter, concurrent writes AtomicLong High-throughput counter, many threads LongAdder Read-heavy single value, rare writes ReentrantReadWriteLock (then benchmark StampedLock) Lock with timeout or fairness ReentrantLock Thread-safe key-value store ConcurrentHashMap Lock-free unbounded queue ConcurrentLinkedQueue Infrequent-write list, concurrent iteration CopyOnWriteArrayList Producer-consumer with backpressure LinkedBlockingQueue Direct task handoff without buffering SynchronousQueue Wait for N external events, one-shot CountDownLatch Fixed threads synchronize at checkpoints CyclicBarrier Dynamic participant count at barrier Phaser Limit concurrent access to N resources Semaphore Two-thread double-buffer swap Exchanger Single-variable atomic with ABA protection AtomicStampedReference

Every class in this table exists because a specific scenario exposed a gap in the one before it. That is the right mental model: not a catalogue to memorise, but a progression of solutions each addressing the failure modes of its predecessor.

Published under Systems Engineering.