Skip to lesson

Choose the right synchronizer

A synchronizer is an object whose only job is to make threads wait for each other in a planned way. Each one answers a different question, so the right choice comes from reading the requirement carefully: wait for what, how many, and how often.

join versus CountDownLatch

join() waits until one particular thread has ended. A CountDownLatch waits until a count of events has happened, no matter which threads produce them or whether those threads keep running afterwards.

Example 1 · A thread that keeps running: join cannot help, a latch can

ReadySignalDemo.javaJava
import java.util.concurrent.CountDownLatch;
public class ReadySignalDemo {    public static void main(String[] args) throws InterruptedException {        CountDownLatch ready = new CountDownLatch(1);
        Thread resultServer = new Thread(() -> {            ready.countDown();                          // "I am ready"            while (!Thread.currentThread().isInterrupted()) {                try {                    Thread.sleep(20);                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                }            }        }, "result-server");        resultServer.start();
        ready.await();                                  // join() here would wait forever        System.out.println("Server ready, still running: " + resultServer.isAlive());
        resultServer.interrupt();        resultServer.join();                            // now join makes sense: it will end        System.out.println("Server stopped, still running: " + resultServer.isAlive());    }}
Output
Server ready, still running: true
Server stopped, still running: false

What this code does

  • The server loads the exam results, calls countDown(), then keeps serving students' requests; its job never ends on its own, so join() would block main forever. The latch waits for the event "ready" instead, and the server keeps running after it.
  • Once main interrupts the server, the thread will end, and join() is the right tool to wait for that.
  • Same program, two waits, two tools: a latch for an event, join() for the end of a thread.

Use join() when you created the threads yourself and simply need them finished. It is the simplest choice, and like a latch it makes the thread's writes visible to you. Use a latch when the threads do not end: thread pool threads stay alive for the next task, and a server thread keeps running after it says "ready". A latch also lets several threads wait for the same event, and await(timeout, unit) reports success as a boolean.

CountDownLatch versus CyclicBarrier

A latch has two roles: some threads count down, other threads wait. It opens once and stays open. A barrier has one role: the same threads arrive and wait for each other, and it resets itself for the next round.

Example 2 · The same three workers with a latch and with a barrier

LatchVsBarrierDemo.javaJava
import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CountDownLatch;import java.util.concurrent.CyclicBarrier;
public class LatchVsBarrierDemo {    static int round = 0;
    public static void main(String[] args) throws InterruptedException {        int[] marks = {70, 85, 60};
        // Latch: main waits once for 3 workers        int[] once = new int[3];        CountDownLatch done = new CountDownLatch(3);        for (int i = 0; i < 3; i++) {            int id = i;            new Thread(() -> {                once[id] = marks[id];                done.countDown();            }).start();        }        done.await();        System.out.println("Latch: main saw total " + (once[0] + once[1] + once[2]));
        // Barrier: the workers wait for each other, 2 rounds, no work for main        int[] bonus = new int[3];        CyclicBarrier endOfRound = new CyclicBarrier(3, () -> {            round++;            System.out.println("Barrier: round " + round + " total " + (bonus[0] + bonus[1] + bonus[2]));        });        Thread[] workers = new Thread[3];        for (int i = 0; i < 3; i++) {            int id = i;            workers[i] = new Thread(() -> {                try {                    for (int r = 1; r <= 2; r++) {                        bonus[id] = marks[id] + 5 * r;   // this round's marks with grace                        endOfRound.await();                    }                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                } catch (BrokenBarrierException e) {                    System.out.println("Round cancelled");                }            });            workers[i].start();        }        for (Thread w : workers) {            w.join();        }    }}
Output
Latch: main saw total 215
Barrier: round 1 total 230
Barrier: round 2 total 245

What this code does

  • With the latch, the workers count down and leave; only main waits, and only once.
  • With the barrier, the workers themselves wait for each other at the end of each round, and the barrier action merges the round. The same barrier serves both rounds.
  • The question "who waits for whom, and how often?" decides the tool: one outside waiter, once → latch; the group itself, every round → barrier.

So the question is "who waits for whom?". "Main waits until 3 workers are done" is a latch. "3 workers wait for each other at the end of every round" is a barrier. A barrier can also run a barrier action each round, and it can break; a latch has neither. You can fake rounds with a new latch per round, but the code is longer and easy to get wrong.

Semaphore versus a lock

A lock (synchronized or ReentrantLock) lets exactly one thread in and has an owner: only the thread that locked may unlock, and the owner may lock again (it is reentrant). A Semaphore lets up to n threads in and has no owner.

Example 3 · Lock versus Semaphore(1): owner and reentrancy

LockVsSemaphoreDemo.javaJava
import java.util.concurrent.Semaphore;import java.util.concurrent.locks.ReentrantLock;
public class LockVsSemaphoreDemo {    public static void main(String[] args) throws InterruptedException {        ReentrantLock lock = new ReentrantLock();        lock.lock();        lock.lock();                                    // the owner may lock again        System.out.println("Lock taken twice by main, hold count: " + lock.getHoldCount());        lock.unlock();        lock.unlock();
        Semaphore single = new Semaphore(1);        single.acquire();        System.out.println("Semaphore taken again by main: " + single.tryAcquire());
        Thread helper = new Thread(single::release);    // any thread may release        helper.start();        helper.join();        System.out.println("Released by another thread, free permits: " + single.availablePermits());
        String[] result = new String[1];        lock.lock();        Thread intruder = new Thread(() -> {            try {                lock.unlock();                          // not the owner            } catch (IllegalMonitorStateException e) {                result[0] = e.getClass().getSimpleName();            }        });        intruder.start();        intruder.join();        lock.unlock();        System.out.println("Another thread unlocking the lock: " + result[0]);    }}
Output
Lock taken twice by main, hold count: 2
Semaphore taken again by main: false
Released by another thread, free permits: 1
Another thread unlocking the lock: IllegalMonitorStateException

What this code does

  • ReentrantLock knows its owner: main can lock it twice (hold count 2), and a different thread that tries to unlock it gets IllegalMonitorStateException.
  • Semaphore(1) only counts permits. main cannot take it a second time (tryAcquire is false; plain acquire() would wait forever), yet any other thread may release it.
  • So protect shared data with a lock, and use a semaphore when you need a count of n, not ownership.

Use a lock to protect shared data, such as a check-then-act on a seat count. Use a semaphore to limit how many threads use a resource, such as 3 calls to a slow API. A Semaphore(1) looks like a lock but is not one: the same thread cannot take it twice, and any thread may release it. The two often work together: a semaphore limits how many threads enter, and a lock or atomic protects the data they change inside.

A decision table for common scenarios

Read the requirement and match its key words to a tool in the list after the code.

Example 4 · Two tools together: fest registration desks

FestRegistrationDemo.javaJava
import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;import java.util.concurrent.atomic.AtomicInteger;
public class FestRegistrationDemo {    public static void main(String[] args) throws InterruptedException {        int students = 6;        CountDownLatch doorsOpen = new CountDownLatch(1);         // start gate        Semaphore desks = new Semaphore(2);                       // at most 2 at the desks        CountDownLatch registered = new CountDownLatch(students);        AtomicInteger atDesk = new AtomicInteger();        AtomicInteger peak = new AtomicInteger();        ExecutorService pool = Executors.newFixedThreadPool(students);
        for (int i = 0; i < students; i++) {            pool.submit(() -> {                try {                    doorsOpen.await();                    desks.acquire();                    try {                        peak.accumulateAndGet(atDesk.incrementAndGet(), Math::max);                        Thread.sleep(80);                         // filling the form                        atDesk.decrementAndGet();                    } finally {                        desks.release();                    }                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                } finally {                    registered.countDown();                }            });        }
        System.out.println("Doors open");        doorsOpen.countDown();        registered.await();        pool.shutdown();        System.out.println("Registered: " + students + ", most at the desks at once: " + peak.get());    }}
Sample output
Doors open
Registered: 6, most at the desks at once: 2

What this code does

  • Each requirement maps to one tool: "everyone starts when the doors open" is a start gate, "only 2 desks" is a Semaphore(2), and "tell me when all are registered" is a CountDownLatch(6).
  • The tasks run on a pool, so join() is not available; the second latch does that job. registered.countDown() sits in finally so it runs on every path.
  • Each tool does one clear job, which keeps the code easy to read. The peak depends on thread timing: it is usually 2, can be lower on a slow or busy computer, and can never be higher than 2.
  • "main waits until N tasks finish, once" → CountDownLatch(N) (or join() for your own threads)
  • "start many threads at the same moment" → CountDownLatch(1) as a start gate
  • "the same group meets after every round" → CyclicBarrier(N), with a barrier action to merge
  • "at most N at the same time" → Semaphore(N)
  • "one at a time, protecting shared data" → synchronized, ReentrantLock or an atomic
  • "the group changes, or the task count is found while running" → Phaser
  • "hand items from producers to consumers" → BlockingQueue

When two tools fit, pick the one whose name says what the code means. A reader seeing CyclicBarrier already knows "rounds"; the same logic built from latches must be studied line by line.

Next step

Check your understanding

11 quick questions