Java : CountDownLatch with Examples

CountDownLatch (Java SE 18 & JDK 18) API Examples.
You will find code examples on most CountDownLatch methods.


Summary

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

Sequence

final long current = System.nanoTime();
final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newFixedThreadPool(2);

try {
    final var latch = new CountDownLatch(2);
    System.out.println("Main Thread : latch count = " + latch.getCount());

    executorService.submit(() -> {
        try {
            System.out.printf("  Thread A : start : %f sec.%n", elapsedSec.getAsDouble());
            TimeUnit.SECONDS.sleep(1);
            System.out.printf("  Thread A : end   : %f sec.%n", elapsedSec.getAsDouble());
        } finally {
            latch.countDown();
            System.out.println("  Thread A : latch count = " + latch.getCount());
        }
        return null;
    });

    executorService.submit(() -> {
        try {
            System.out.printf("  Thread B : start : %f sec.%n", elapsedSec.getAsDouble());
            TimeUnit.SECONDS.sleep(2);
            System.out.printf("  Thread B : end   : %f sec.%n", elapsedSec.getAsDouble());
        } finally {
            latch.countDown();
            System.out.println("  Thread B : latch count = " + latch.getCount());
        }
        return null;
    });

    System.out.printf("Main Thread : await start : %f sec.%n", elapsedSec.getAsDouble());
    latch.await();
    System.out.printf("Main Thread : await end : %f sec.%n", elapsedSec.getAsDouble());

} finally {
    executorService.shutdown();
}

final var term = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + term);

// Result
// ↓
//Main Thread : latch count = 2
//  Thread A : start : 0.004276 sec.
//  Thread B : start : 0.004439 sec.
//Main Thread : await start : 0.004305 sec.
//  Thread A : end   : 1.006230 sec.
//  Thread A : latch count = 1
//  Thread B : end   : 2.007936 sec.
//  Thread B : latch count = 0
//Main Thread : await end : 2.008358 sec.
//term : true

Constructors

CountDownLatch (int count)

Constructs a CountDownLatch initialized with the given count.

final long current = System.nanoTime();
final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();

try {
    final var latch = new CountDownLatch(1);

    executorService.submit(() -> {
        try {
            System.out.printf("  sleep start : %f sec.%n", elapsedSec.getAsDouble());
            TimeUnit.SECONDS.sleep(1);
            System.out.printf("  sleep end   : %f sec.%n", elapsedSec.getAsDouble());
        } finally {
            latch.countDown();
        }
        return null;
    });

    System.out.printf("await start : %f sec.%n", elapsedSec.getAsDouble());
    latch.await();
    System.out.printf("await end   : %f sec.%n", elapsedSec.getAsDouble());

} finally {
    executorService.shutdown();
}

final var term = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + term);

// Result
// ↓
//await start : 0.001962 sec.
//  sleep start : 0.002234 sec.
//  sleep end   : 1.015228 sec.
//await end   : 1.015626 sec.
//term : true

Methods

void await ()

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.

Please see also : Summary , CountDownLatch(int count)

final long current = System.nanoTime();
final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newFixedThreadPool(2);

try {
    final var latch = new CountDownLatch(1);

    final var future = executorService.submit(() -> {
        try {
            System.out.printf("Thread A : start : %f sec.%n", elapsedSec.getAsDouble());
            latch.await();

        } catch (InterruptedException e) {
            System.out.println("Thread A : InterruptedException!");
        } finally {
            System.out.printf("Thread A : end : %f sec.%n", elapsedSec.getAsDouble());
        }
    });

    executorService.submit(() -> {
        System.out.printf("Thread B : sleep start : %f sec.%n", elapsedSec.getAsDouble());
        TimeUnit.SECONDS.sleep(5);
        System.out.printf("Thread B : sleep end   : %f sec.%n", elapsedSec.getAsDouble());

        final var ret = future.cancel(true);
        System.out.println("Thread B : cancel : " + ret);

        return null;
    });

} finally {
    executorService.shutdown();
}

final var term = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + term);

// Result
// ↓
//Thread A : start : 0.002028 sec.
//Thread B : sleep start : 0.002209 sec.
//Thread B : sleep end   : 5.012301 sec.
//Thread A : InterruptedException!
//Thread A : end : 5.013477 sec.
//Thread B : cancel : true
//term : true

boolean await (long timeout, TimeUnit unit)

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted, or the specified waiting time elapses.

Please see also : await()

final long current = System.nanoTime();
final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();

try {
    final var latch = new CountDownLatch(1);

    executorService.submit(() -> {
        try {
            System.out.printf("Thread A : sleep start : %f sec.%n", elapsedSec.getAsDouble());
            TimeUnit.SECONDS.sleep(2);
            System.out.printf("Thread A : sleep end   : %f sec.%n", elapsedSec.getAsDouble());
        } finally {
            latch.countDown();
        }
        return null;
    });

    final var ret = latch.await(5, TimeUnit.SECONDS);
    System.out.printf("await ret = %b : %f sec.%n", ret, elapsedSec.getAsDouble());

} finally {
    executorService.shutdown();
}

final var term = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + term);

// Result
// ↓
//Thread A : sleep start : 0.002863 sec.
//Thread A : sleep end   : 2.005293 sec.
//await ret = true : 2.005695 sec.
//term : true

An example with timeout.

final long current = System.nanoTime();
final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();

try {
    final var latch = new CountDownLatch(1);

    executorService.submit(() -> {
        try {
            System.out.printf("Thread A : sleep start : %f sec.%n", elapsedSec.getAsDouble());
            TimeUnit.SECONDS.sleep(7);
            System.out.printf("Thread A : sleep end   : %f sec.%n", elapsedSec.getAsDouble());
        } finally {
            latch.countDown();
        }
        return null;
    });

    final var ret = latch.await(5, TimeUnit.SECONDS);
    System.out.printf("await ret = %b : %f sec.%n", ret, elapsedSec.getAsDouble());

} finally {
    executorService.shutdown();
}

final var term = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + term);

// Result
// ↓
//Thread A : sleep start : 0.002323 sec.
//await ret = false : 5.009722 sec.
//Thread A : sleep end   : 7.009743 sec.
//term : true

void countDown ()

Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

Please see : Summary , CountDownLatch(int count)

long getCount ()

Returns the current count.

Please see : Summary

String toString ()

Returns a string identifying this latch, as well as its state.

final var latch = new CountDownLatch(2);

final var str1 = latch.toString();
System.out.println(str1); // java.util.concurrent.CountDownLatch@2de56eb2[Count = 2]

latch.countDown();

final var str2 = latch.toString();
System.out.println(str2); // java.util.concurrent.CountDownLatch@2de56eb2[Count = 1]

latch.countDown();

final var str3 = latch.toString();
System.out.println(str3); // java.util.concurrent.CountDownLatch@2de56eb2[Count = 0]

Related posts

To top of page