Hackforge Academy

Category: java

CountDownLatch Introduction

Published on 27 Oct 2026

Explanation

CountDownLatch allows one or more threads to wait until a count reaches zero. The count can only decrease, so the same latch cannot be reset for another round of work.

Code:

import java.util.concurrent.CountDownLatch;

public class LatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);
        new Thread(() -> { System.out.println("Task A"); latch.countDown(); }).start();
        new Thread(() -> { System.out.println("Task B"); latch.countDown(); }).start();
        latch.await();
        System.out.println("Both tasks finished");
    }
}

Explanation

CyclicBarrier lets a fixed number of threads wait for one another at a common barrier point. Once all parties arrive, they are released together, and the barrier can be reused for another phase.

Code:

import java.util.concurrent.CyclicBarrier;

public class BarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(2, () -> System.out.println("Both arrived"));
        Runnable task = () -> {
            try { System.out.println(Thread.currentThread().getName() + " ready"); barrier.await(); }
            catch (Exception e) { Thread.currentThread().interrupt(); }
        };
        new Thread(task).start();
        new Thread(task).start();
    }
}

Explanation

CountDownLatch is useful when a coordinator waits for several independent tasks to finish. CyclicBarrier is useful when a group of worker threads must meet at a shared point before continuing to the next phase.

Code:

import java.util.concurrent.*;

public class LatchBarrierDifference {
    public static void main(String[] args) throws Exception {
        CountDownLatch startSignal = new CountDownLatch(1);
        Thread worker = new Thread(() -> {
            try { startSignal.await(); System.out.println("Started"); }
            catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        });
        worker.start();
        startSignal.countDown();
        worker.join();
    }
}

Explanation

A CountDownLatch can keep a startup coordinator waiting until required initialization tasks complete. Each task decrements the count when ready, and the coordinator continues after the count reaches zero.

Code:

import java.util.concurrent.CountDownLatch;

public class StartupLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch ready = new CountDownLatch(2);
        Runnable init = () -> { System.out.println("Initialized " + Thread.currentThread().getName()); ready.countDown(); };
        new Thread(init, "Database").start();
        new Thread(init, "Cache").start();
        ready.await();
        System.out.println("Application ready");
    }
}

Explanation

A CyclicBarrier can coordinate iterative calculations in which each worker completes a phase before any worker begins the next. If a party fails to arrive, the other parties may wait until timeout or the barrier is broken.

Code:

import java.util.concurrent.CyclicBarrier;

public class PhasedWorkDemo {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(2);
        Runnable worker = () -> {
            try {
                for (int phase = 1; phase <= 2; phase++) {
                    System.out.println(Thread.currentThread().getName() + " phase " + phase);
                    barrier.await();
                }
            } catch (Exception e) { Thread.currentThread().interrupt(); }
        };
        new Thread(worker).start();
        new Thread(worker).start();
    }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community