Languages
[Edit]
EN

Java concurrency - avoid busy wait using CountDownLatch (inter-thread communication)

2 points
Created by:
Broncono
466

In this article we would like to show to to avoid busy wait in java using CountDownLatch.

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class CountDownLatchExample {

    private final CountDownLatch countDownLatch = new CountDownLatch(2);

    private void executeTasks() throws InterruptedException {

        // Task 1
        Thread thread1 = new Thread(() -> {
            try {
                simulateTask(300);
            } finally {
                countDownLatch.countDown();
                System.out.println(getThreadName() + " - Task 1 done");
            }
        });

        // Task 2
        Thread thread2 = new Thread(() -> {
            try {
                simulateTask(100);
            } finally {
                countDownLatch.countDown();
                System.out.println(getThreadName() + " - Task 2 done");
            }
        });

        thread1.start();
        thread2.start();

        System.out.println(getThreadName() + " - waiting to be notified 2 times");

        // Causes the current thread to wait until the latch has counted down
        // to zero, unless the thread is interrupted.
        // If the current count is zero then this method returns immediately.
        countDownLatch.await();
        System.out.println(getThreadName() + " - notified");
    }

    private String getThreadName() {
        return Thread.currentThread().getName();
    }

    private void simulateTask(int timeout) {
        sleep(timeout);
    }

    private void sleep(int timeout) {
        try {
            TimeUnit.MILLISECONDS.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new CountDownLatchExample().executeTasks();
    }
}

Output:

main - waiting to be notified 2 times
Thread-1 - Task 2 done
Thread-0 - Task 1 done
main - notified

 

See also

  1. What is busy waiting lock?

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java concurrency

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join