CountDownLatch: wait for N tasks
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A CountDownLatch is a counter that threads can wait on. It starts at a number N, each finished task calls countDown() to subtract one, and any thread that calls await() waits until the count reaches zero.
countDown() and await()
A CountDownLatch lets threads wait until a counter, started at N, is counted down to zero by other threads finishing their work.
new CountDownLatch(n) creates a latch with a count of n. countDown() subtracts one and never blocks. await() blocks the calling thread until the count is zero, then returns.
Example 1 · Wait for three teachers to finish checking
import java.util.concurrent.CountDownLatch;
public class AnswerSheetDemo { static void work(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) throws InterruptedException { int[][] marks = { {72, 65, 88}, {91, 54}, {47, 80, 69, 75} }; int[] totals = new int[marks.length]; CountDownLatch done = new CountDownLatch(marks.length);
for (int i = 0; i < marks.length; i++) { int t = i; new Thread(() -> { work(40L * (t + 1)); // checking takes some time for (int m : marks[t]) { totals[t] += m; } done.countDown(); // this teacher is finished }, "teacher-" + (i + 1)).start(); }
System.out.println("Waiting for " + marks.length + " teachers..."); done.await(); // blocks until the count is 0 System.out.println("Count is now " + done.getCount());
int grand = 0; for (int t = 0; t < totals.length; t++) { System.out.println("teacher-" + (t + 1) + " total: " + totals[t]); grand += totals[t]; } System.out.println("All sheets checked. Grand total: " + grand); }}Waiting for 3 teachers... Count is now 0 teacher-1 total: 225 teacher-2 total: 145 teacher-3 total: 271 All sheets checked. Grand total: 641
What this code does
- The latch starts at 3. Each teacher thread adds up its own sheets and calls
countDown()once.mainblocks inawait()until the third call brings the count to 0. totalsis a plain array with novolatileorsynchronized. Reading it afterawait()is still safe, because each write happened before that thread'scountDown().mainprints the results in a fixed order after waiting, so the output is the same on every run even though the threads finish at different times.
Think of a class teacher who waits for three subject teachers to finish checking answer sheets. Each subject teacher says "done" once. When all three have said it, the class teacher prepares the result. Nobody has to keep asking "are you done yet?". The latch also makes data safe to read. Everything a thread did before countDown() is visible to the thread that returns from await(). This is a happens-before rule, the same idea as with join(), so a plain int[] filled by the workers needs no volatile here.
Predict the output
What is the count?
Read the program and pick what it prints.
Round 1 of 2
Only the calls shown happen.
await() throws the checked InterruptedException, so main either declares throws InterruptedException or catches it.Waiting for services to start
A common use of a latch is startup: the main thread waits until every service it needs says "I am ready". A service here is a part of the app that takes time to start, such as a database connection or a payment gateway.
Example 2 · Open the booking app when all services are ready
import java.util.concurrent.CountDownLatch;
class Service implements Runnable { private final String name; private final long startupMs; private final CountDownLatch ready;
Service(String name, long startupMs, CountDownLatch ready) { this.name = name; this.startupMs = startupMs; this.ready = ready; }
@Override public void run() { try { Thread.sleep(startupMs); // connecting, loading data... System.out.println(name + " is ready"); ready.countDown(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }}
public class StartupDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch ready = new CountDownLatch(3);
new Thread(new Service("Database", 120, ready), "db").start(); new Thread(new Service("Seat cache", 40, ready), "cache").start(); new Thread(new Service("UPI gateway", 80, ready), "upi").start();
System.out.println("Booking app starting..."); ready.await(); System.out.println("All services ready. Tatkal booking is open."); }}Booking app starting... Seat cache is ready UPI gateway is ready Database is ready All services ready. Tatkal booking is open.
What this code does
- Each
Servicesleeps to act like a slow startup, prints a line and counts down. The order of the three "is ready" lines depends on timing and can change from run to run. - The last line is always last:
mainprints it only afterawait()returns, and that happens only after all three services have counted down. countDown()is called only when the service really started. If a service fails, the count stays above zero, which the next example handles with a timeout.
Example 3 · Do not wait forever: await with a timeout
import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;
public class StartupTimeoutDemo { static void startService(String name, long startupMs, CountDownLatch ready) { Thread t = new Thread(() -> { try { Thread.sleep(startupMs); ready.countDown(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, name); t.setDaemon(true); // a stuck service must not keep the JVM alive t.start(); }
public static void main(String[] args) throws InterruptedException { CountDownLatch ready = new CountDownLatch(3); startService("db", 30, ready); startService("cache", 20, ready); startService("upi", 60_000, ready); // UPI gateway is stuck today
System.out.println("Waiting up to 500 ms for 3 services"); boolean allUp = ready.await(500, TimeUnit.MILLISECONDS);
if (allUp) { System.out.println("All services ready"); } else { System.out.println("Not ready after 500 ms: " + ready.getCount() + " service(s) still starting"); System.out.println("Showing: Booking temporarily unavailable"); } }}Waiting up to 500 ms for 3 services Not ready after 500 ms: 1 service(s) still starting Showing: Booking temporarily unavailable
What this code does
await(500, TimeUnit.MILLISECONDS)returnsfalsebecause the stuck UPI service has not counted down by then. Plainawait()would block for a full minute here, or forever if the service never started.getCount()reports how many services are missing, so the app can show a clear message instead of freezing.- A latch does not stop or cancel the threads that use it. The stuck thread is a daemon thread, so the program can end without waiting for it. This output assumes the quick threads finish well inside the timeout; on a very slow or busy computer the result can differ.
Each service calls countDown() once it is ready. The main thread calls await() and opens the app only after the count reaches zero. A service can also hang or fail and never count down. await(timeout, unit) waits at most that long and returns a boolean: true if the count reached zero, false if time ran out. getCount() then tells you how many are still missing.
Order of execution
Open the app when services are ready
Put the steps in the order they happen.
A start gate so threads begin together
A start gate is a latch with a count of 1. Worker threads call await() on it and block. When the main thread calls countDown() once, the gate opens and all of them continue at almost the same moment.
Example 4 · A start gate for the Tatkal rush
import java.util.concurrent.CountDownLatch;import java.util.concurrent.atomic.AtomicInteger;
public class TatkalGateDemo { public static void main(String[] args) throws InterruptedException { int users = 5; AtomicInteger seatsLeft = new AtomicInteger(2); AtomicInteger confirmed = new AtomicInteger(); AtomicInteger waitlisted = new AtomicInteger();
CountDownLatch ready = new CountDownLatch(users); CountDownLatch startGate = new CountDownLatch(1); // opens at 10:00 CountDownLatch finished = new CountDownLatch(users);
for (int i = 1; i <= users; i++) { new Thread(() -> { ready.countDown(); try { startGate.await(); // everyone blocks here if (seatsLeft.decrementAndGet() >= 0) { confirmed.incrementAndGet(); } else { waitlisted.incrementAndGet(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { finished.countDown(); } }, "user-" + i).start(); }
ready.await(); System.out.println(users + " users waiting for 10:00 AM"); startGate.countDown(); // one call opens the gate System.out.println("10:00 AM: Tatkal window open"); finished.await(); System.out.println("Confirmed: " + confirmed.get() + ", Waitlisted: " + waitlisted.get()); }}5 users waiting for 10:00 AM 10:00 AM: Tatkal window open Confirmed: 2, Waitlisted: 3
What this code does
readymakes sure all 5 threads have started and reached the gate beforemainopens it. Then a singlestartGate.countDown()releases all of them together, so they really compete for the 2 seats.- Which users get the seats changes from run to run, but the totals do not:
decrementAndGetis atomic, so exactly 2 are confirmed and 3 are waitlisted. finished.countDown()sits infinally, so the count reaches zero even if a user thread is interrupted.mainnever waits forever.
This is useful for load tests and for showing race conditions. Without a gate, the first thread may finish before the last one even starts, so they never really compete. The full pattern uses three latches: ready (each worker says "I am at the gate"), start gate (count 1, opened by main) and finished (each worker says "I am done").
A latch is used only once
A CountDownLatch cannot be reset. Once the count reaches zero, it stays at zero. Every later await() returns at once, and extra countDown() calls do nothing.
Example 5 · Mistake: reusing a latch for a second round
import java.util.concurrent.CountDownLatch;
public class LatchOnceDemo { static void pause(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static Thread[] startWorkers(CountDownLatch latch, int[] result, int a, int b) { int[] values = {a, b}; Thread[] threads = new Thread[2]; for (int i = 0; i < 2; i++) { int k = i; threads[i] = new Thread(() -> { pause(100); result[k] = values[k]; latch.countDown(); }, "worker-" + (i + 1)); threads[i].start(); } return threads; }
public static void main(String[] args) throws InterruptedException { int[] result = new int[2]; CountDownLatch latch = new CountDownLatch(2);
startWorkers(latch, result, 10, 20); latch.await(); System.out.println("Round 1 sum: " + (result[0] + result[1]));
latch.countDown(); // extra call at zero: does nothing System.out.println("Count before round 2: " + latch.getCount());
Thread[] round2 = startWorkers(latch, result, 30, 40); latch.await(); // count is already 0: returns at once System.out.println("Round 2 sum (wrong): " + (result[0] + result[1])); for (Thread t : round2) { t.join(); }
CountDownLatch fresh = new CountDownLatch(2); // the fix: a new latch startWorkers(fresh, result, 30, 40); fresh.await(); System.out.println("Round 2 sum with a new latch: " + (result[0] + result[1])); }}Round 1 sum: 30 Count before round 2: 0 Round 2 sum (wrong): 30 Round 2 sum with a new latch: 70
What this code does
- After round 1 the count is 0 for good. The extra
countDown()changes nothing, and the secondawait()returns at once, somainreads round 1's numbers while the workers are still sleeping (each one's work takes 100 ms). - The wrong line prints 30, the old sum, instead of 70. Reading the array while workers may still write it is also a data race, so the value is not even guaranteed.
- The fix is one line: a fresh
CountDownLatchfor each round. If the same group of threads must meet again and again, useCyclicBarrierinstead. The wrong sum depends on timing: it is usually 30 (the old numbers), but on a slow computer it can differ.
So a latch fits a one-time event: "the app has started", "all files are downloaded", "the gate is open". If you reuse an old latch for a second round of work, await() no longer waits and you read results that are not ready yet. For repeated rounds, create a new latch for each round, or use CyclicBarrier, which resets itself. The next lesson covers it.
Fix the error
Fix the compile errors
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
A report job waits on a latch.
Error
ReportJob.java:7: error: unreported exception InterruptedException; must be caught or declared to be thrown
done.await();
^Next step
Check your understanding
11 quick questions