Core Java · 5. Multithreading, lesson 4 of 7

Concurrent collections and synchronizers: ConcurrentHashMap, CountDownLatch, CyclicBarrier and Semaphore

Advanced5 min read@since 9Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

java.util.concurrent gives you tested building blocks, so you rarely need low-level wait and notify:

  • Atomics (AtomicInteger, AtomicLong, AtomicReference, LongAdder): lock-free updates such as incrementAndGet and compareAndSet.
  • CountDownLatch: threads wait until a count reaches zero, for example until three caches have warmed up.
  • Semaphore: limits how many threads use a resource at once, for example at most ten calls to a partner API.
  • CyclicBarrier and Phaser: threads wait for each other at a checkpoint, repeatedly.
  • BlockingQueue: producer-consumer hand-off; put waits when the queue is full and take waits when it's empty.
  • ConcurrentHashMap and CopyOnWriteArrayList: thread-safe collections.

Pick the highest-level tool that fits; it's much easier to get right than locks.

Threads lab

ConcurrentHashMap in practice

The thread-safe map for shared data. The key is to use its atomic methods instead of separate "check, then act" calls. It doesn't allow null keys or values, and its iterators never throw ConcurrentModificationException. The comparison lesson "HashMap vs ConcurrentHashMap" explains how it works inside.

Java
ConcurrentHashMap<String, LongAdder> views = new ConcurrentHashMap<>();
views.computeIfAbsent("/learn/streams", k -> new LongAdder()).increment();   // hot counter

ConcurrentHashMap<String, Integer> stock = new ConcurrentHashMap<>();
stock.merge("pen", 10, Integer::sum);          // add 10, atomically
stock.computeIfPresent("pen", (k, qty) -> qty > 0 ? qty - 1 : null);   // returning null removes the key
ConcurrentHashMap lab

CountDownLatch: wait until N things have happened

A latch starts at a count. Threads call countDown() when their part is done; threads calling await() block until the count reaches zero. It's one-shot: it can't be reset. Typical use: start serving only after several caches have warmed up. Put countDown() in a finally block, so a failing task doesn't leave everyone waiting forever.

Java
CountDownLatch ready = new CountDownLatch(3);

for (String cache : List.of("courses", "lessons", "prices")) {
    pool.submit(() -> {
        try {
            warmUp(cache);
        } finally {
            ready.countDown();                  // always count down, even on failure
        }
    });
}

if (!ready.await(30, TimeUnit.SECONDS)) {       // wait at most 30 seconds
    log.warn("Starting before all caches were warm");
}

CyclicBarrier: threads wait for each other

A barrier makes a fixed number of threads (the "parties") wait for each other at a checkpoint; when the last one arrives, all continue. An optional barrier action runs once each time the barrier trips, and the barrier then resets automatically, so it suits work done in rounds. If one waiting thread is interrupted or times out, the others get BrokenBarrierException.

Java
int workers = 3;
CyclicBarrier roundDone = new CyclicBarrier(workers, () -> System.out.println("Round merged"));

for (int w = 0; w < workers; w++) {
    int id = w;
    new Thread(() -> {
        for (int round = 1; round <= 2; round++) {
            processChunk(id, round);
            try {
                roundDone.await();              // wait for the other workers
            } catch (InterruptedException | BrokenBarrierException e) {
                return;
            }
        }
    }).start();
}

Semaphore: limit how many at once

A semaphore holds a number of permits. acquire() takes one (waiting if none are left) and release() gives it back. Use it to cap concurrent access, for example at most 5 calls to a partner API at a time, even with hundreds of virtual threads. Always release in finally. tryAcquire(timeout, unit) gives up instead of waiting forever.

Java
Semaphore partnerApi = new Semaphore(5);        // at most 5 calls in flight

String callPartner(String orderId) throws InterruptedException {
    if (!partnerApi.tryAcquire(2, TimeUnit.SECONDS)) {
        throw new IllegalStateException("Partner API busy, try again");
    }
    try {
        return httpCall(orderId);
    } finally {
        partnerApi.release();                   // always give the permit back
    }
}

CountDownLatch vs CyclicBarrier

  • Who waits: with a latch, one or more threads wait for events counted down by others; with a barrier, the participating threads wait for each other.
  • Reuse: a latch is one-shot; a barrier resets after each round.
  • Counting: anyone can count a latch down, even the same thread several times; a barrier needs exactly N different threads to arrive.
  • Action: a barrier can run a barrier action each round; a latch can't.
  • Failure: a barrier breaks for everyone if one participant fails; a latch just stays unreleased (use a timeout).

Phaser combines both ideas and allows parties to join and leave.

BlockingQueue: producers and consumers

A BlockingQueue hands work from producer threads to consumer threads: put() waits when the queue is full, take() waits when it's empty, so neither side needs manual locking. A bounded ArrayBlockingQueue also gives back-pressure: fast producers are slowed down instead of filling memory. A special "poison pill" item is a simple way to tell consumers to stop.

Java
BlockingQueue<String> emails = new ArrayBlockingQueue<>(100);

Thread producer = new Thread(() -> {
    try {
        for (String user : users) emails.put(user);   // waits if 100 are already queued
        emails.put("STOP");                           // poison pill
    } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});

Thread consumer = new Thread(() -> {
    try {
        for (String user; !(user = emails.take()).equals("STOP"); ) sendWelcomeEmail(user);
    } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
BlockingQueue lab

Example

Java
ExecutorService pool = Executors.newFixedThreadPool(4);

// Wait for three warm-up tasks
CountDownLatch ready = new CountDownLatch(3);
for (String cache : List.of("courses", "users", "prices")) {
    pool.submit(() -> {
        try { warmUp(cache); } finally { ready.countDown(); }
    });
}
ready.await(10, TimeUnit.SECONDS);

// At most two calls at a time to a rate-limited partner API
Semaphore permits = new Semaphore(2);
Runnable call = () -> {
    try {
        permits.acquire();
        try { partnerApi.fetch(); } finally { permits.release(); }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
};

// Producer and consumer
BlockingQueue<String> emails = new LinkedBlockingQueue<>(100);
pool.submit(() -> { emails.put("welcome:asha@example.com"); return null; });
pool.submit(() -> { send(emails.take()); return null; });

LongAdder pageViews = new LongAdder();
pageViews.increment();                   // scales better than AtomicLong under heavy contention

Common mistake

Calling countDown() outside a finally block. If the task throws, the latch never reaches zero and await() blocks until it times out.

Under the hood

Atomics rely on the CPU's compare-and-swap instruction: read, compute, and write only if nobody changed the value in between, retrying otherwise. Under heavy contention many threads keep retrying, which is why LongAdder spreads updates across cells and sums them when read. With virtual threads, a Semaphore is the standard way to protect scarce resources such as database connections.

Check yourself

Which tool limits how many threads use a resource at once?

How this connects

Part of Crack the Java interview, Upgrade from Java 8 to Java 25, Multithreading: beginner to advanced.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.