Tech Interview RoomStudy guides

Java 21

Java 21: Build a thread-safe request counter under 100,000 virtual threads. Compare unsynchronised, synchronized, ReentrantLock, AtomicLong and LongAdder.

Advanced · 2 min read · Lesson 6 of 8 in Java 21

Problem

Every request (each on its own virtual thread) increments a shared counter. Which implementation is correct, and which is fastest under heavy contention? Also: which ones interact badly with virtual threads?

java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

interface Counter { void increment(); long get(); }

final class Load {
    static long run(Counter c, int tasks, int incrementsPerTask) {
        try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < tasks; i++) ex.submit(() -> { for (int j = 0; j < incrementsPerTask; j++) c.increment(); });
        }   // waits for all tasks
        return c.get();
    }
}

Approach 1: Plain field (wrong)

count++ is read-modify-write, so concurrent increments overwrite each other ("lost updates"). It is not even guaranteed to be visible to other threads.

java
class UnsafeCounter implements Counter {
    private long count;
    public void increment() { count++; }
    public long get() { return count; }
}

Approach 2: synchronized (correct, simple)

Mutual exclusion plus visibility. Fine here because the critical section never blocks. On Java 21, blocking inside synchronized (I/O, sleep) would pin the carrier thread (fixed in JDK 24 by JEP 491).

java
class SyncCounter implements Counter {
    private long count;
    public synchronized void increment() { count++; }
    public synchronized long get() { return count; }
}

Approach 3: ReentrantLock (correct, virtual-thread friendly)

Same guarantees; waiting threads park without pinning, and it offers tryLock with timeouts. Use it when the critical section may block on Java 21.

java
import java.util.concurrent.locks.ReentrantLock;

class LockCounter implements Counter {
    private final ReentrantLock lock = new ReentrantLock();
    private long count;
    public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } }
    public long get() { lock.lock(); try { return count; } finally { lock.unlock(); } }
}

Approach 4: AtomicLong (lock-free CAS)

incrementAndGet uses a hardware compare-and-swap loop: no locks, no pinning. Under extreme contention many CAS attempts fail and retry on the same cache line.

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

class AtomicCounter implements Counter {
    private final AtomicLong count = new AtomicLong();
    public void increment() { count.incrementAndGet(); }
    public long get() { return count.get(); }
}

Approach 5: LongAdder (optimal for write-heavy counters)

Spreads increments over several padded cells (one per contending thread group) and sums them on read. Writes scale with cores; sum() is slightly more expensive and not an atomic snapshot, which is fine for metrics.

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

class AdderCounter implements Counter {
    private final LongAdder count = new LongAdder();
    public void increment() { count.increment(); }
    public long get() { return count.sum(); }
}

class CounterDemo {
    public static void main(String[] args) {
        int tasks = 100_000, each = 10;
        long expected = (long) tasks * each;
        for (Counter c : new Counter[] {new UnsafeCounter(), new SyncCounter(), new LockCounter(), new AtomicCounter(), new AdderCounter()}) {
            long t = System.nanoTime();
            long result = Load.run(c, tasks, each);
            System.out.printf("%-14s %,d of %,d (%s) in %d ms%n", c.getClass().getSimpleName(), result, expected,
                result == expected ? "correct" : "LOST UPDATES possible", (System.nanoTime() - t) / 1_000_000);
        }
    }
}

Feasible → optimal

  1. Unsynchronised: incorrect; never acceptable for shared mutable state.
  2. synchronized / ReentrantLock: correct; locks serialise every increment. Prefer ReentrantLock on Java 21 when the critical section can block.
  3. AtomicLong: correct and lock-free; best when you need an exact value on every read (sequence numbers).
  4. LongAdder: correct and fastest under heavy write contention; the standard choice for counters and metrics (Micrometer counters use it).

Follow-up questions interviewers ask

Try answering each one before you open it.

Does the unsafe counter always lose updates?

No. It is a race, so results vary between runs and machines. With virtual threads on a few carrier threads, interleavings may be rare in a short test and the bug can pass CI, then lose counts under production load. That is why thread safety must be reasoned about (or checked with tools such as jcstress), not demonstrated by a passing test.

How would you implement a per-key counter, such as requests per endpoint?

ConcurrentHashMap<String, LongAdder> counts with counts.computeIfAbsent(endpoint, k -> new LongAdder()).increment(): the map handles concurrent key creation atomically and each LongAdder absorbs contention for its key. Bound the number of keys (no user ids as keys), or use Micrometer, which does exactly this with tags.