Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Concurrency

    Coordination Tools

    CountDownLatch(n) — threads call countDown(); await() blocks until the count reaches 0. One-shot.

    Chapter 9 of 123 min read

    The Plain Picture#

    • A starting gun that fires only after all 3 runners say "ready". (CountDownLatch)

    • A car park with 2 spaces: a car enters only if a space is free, and leaves one when it goes. (Semaphore)

    • A tour group that waits at each landmark until everyone has caught up, then moves on together. (CyclicBarrier)

    The Real Names and Uses#

    CountDownLatch(n) — threads call countDown(); await() blocks until the count reaches 0. One-shot.

    Java
    CountDownLatch ready = new CountDownLatch(3);
    
    for (int i = 0; i < 3; i++) {
        int id = i;
        pool.submit(() -> {
            System.out.println("service " + id + " warmed up");
            ready.countDown();
        });
    }
    
    ready.await();
    
    System.out.println("all services ready");
    Output
    service 1 warmed up
    service 0 warmed up        ← order varies — they ran concurrently
    service 2 warmed up
    all services ready         ← only after all three

    Semaphore(permits) — acquire() takes a permit (waiting if none are left), release() returns it. Perfect for limiting concurrency — for example, the AI provider allows only 2 simultaneous requests from StudyBuddy:

    Java
    Semaphore aiSlots = new Semaphore(2);
    
    // each of 6 tasks:
    aiSlots.acquire();
    
    try {
        callAiApi();
    } finally {
        aiSlots.release();
    }
    Output
    semaphore(2): max concurrent AI calls = 2

    Six tasks, never more than two in flight. (Rate limiting across many servers needs a shared store like Redis instead — Rate Limiting and API Gateways (coming soon).)

    CyclicBarrier(n) — n threads each call await() and all are released together when the n-th arrives; reusable for rounds (e.g. parallel simulation steps). Phaser is a more flexible version.

    Check yourself

    2 questions
    1

    Which tool would you use to cap simultaneous calls to an external API at 5?

    Show answer

    Semaphore(5), with acquire before and release in finally after each call.

    2

    CountDownLatch vs CyclicBarrier?

    Show answer

    A latch is one-shot and lets threads wait for a count of events; a barrier makes a fixed group of threads wait for each other, and can be reused for many rounds.