Java concurrency: Countdown latch vs Cyclic barrie

2020-01-26 12:38发布

I was reading through the java.util.concurrent API, and found that

  • CountDownLatch: A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
  • CyclicBarrier: A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

To me both seems equal, but I am sure there is much more to it.

For example, in CoundownLatch, the countdown value could not be reset, that can happen in the case of CyclicBarrier.

Is there any other difference between the two?
What are the use cases where someone would want to reset the value of countdown?

14条回答
手持菜刀,她持情操
2楼-- · 2020-01-26 12:46

The main difference is documented right in the Javadocs for CountdownLatch. Namely:

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

source 1.6 Javadoc

查看更多
Ridiculous、
3楼-- · 2020-01-26 12:48

This question has been adequately answered already, but I think I can value-add a little by posting some code.

To illustrate the behaviour of cyclic barrier, I have made some sample code. As soon as the barrier is tipped, it is automatically reset so that it can be used again (hence it is "cyclic"). When you run the program, observe that the print outs "Let's play" are triggered only after the barrier is tipped.

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierCycles {

    static CyclicBarrier barrier;

    public static void main(String[] args) throws InterruptedException {
        barrier = new CyclicBarrier(3); 

        new Worker().start();
        Thread.sleep(1000);
        new Worker().start();
        Thread.sleep(1000);
        new Worker().start();
        Thread.sleep(1000);

        System.out.println("Barrier automatically resets.");

        new Worker().start();
        Thread.sleep(1000);
        new Worker().start();
        Thread.sleep(1000);
        new Worker().start();
    }

}


class Worker extends Thread {
    @Override
    public void run() {
        try {
            CyclicBarrierCycles.barrier.await();
            System.out.println("Let's play.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
查看更多
祖国的老花朵
4楼-- · 2020-01-26 12:49

One major difference is that CyclicBarrier takes an (optional) Runnable task which is run once the common barrier condition is met.

It also allows you to get the number of clients waiting at the barrier and the number required to trigger the barrier. Once triggered the barrier is reset and can be used again.

For simple use cases - services starting etc... a CountdownLatch is fine. A CyclicBarrier is useful for more complex co-ordination tasks. An example of such a thing would be parallel computation - where multiple subtasks are involved in the computation - kind of like MapReduce.

查看更多
Explosion°爆炸
5楼-- · 2020-01-26 12:52

I think that the JavaDoc has explained the differences explicitly. Most people know that CountDownLatch can not be reset, however, CyclicBarrier can. But this is not the only difference, or the CyclicBarrier could be renamed to ResetbleCountDownLatch. We should tell the differences from the perspective of their goals, which are described in JavaDoc

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

CyclicBarrier: A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

In countDownLatch, there is one or more threads, that are waiting for a set of other threads to complete. In this situation, there are two types of threads, one type is waiting, another type is doing something, after finishes their tasks, they could be waiting or just terminated.

In CyclicBarrier, there are only one type of threads, they are waiting for each other, they are equal.

查看更多
放荡不羁爱自由
6楼-- · 2020-01-26 12:52

One obvious difference is, only N threads can await on a CyclicBarrier of N to be release in one cycle. But unlimited number of threads can await on a CountDownLatch of N. The count down decrement can be done by one thread N times or N threads one time each or combinations.

查看更多
Explosion°爆炸
7楼-- · 2020-01-26 12:55

CountDownLatch is a count down of anything; CyclicBarrier is a count down for thread only

assume there are 5 worker threads and one shipper thread, and when workers produce 100 items, shipper will ship them out.

For CountDownLatch, the counter can be on workers or items

For CyclicBarrier, the counter can only on workers

If a worker falls infinite sleep, with CountDownLatch on items, Shipper can ship; However, with CyclicBarrier, Shipper can never be called

查看更多
登录 后发表回答