What does a CyclicBarrier do

Like CountDownLatch, CyclicBarrier is a class under the java.util.Concurrent package; As you can see from the class name, this is a Cylcic Barrier that blocks a group of threads when they reach a Barrier (synchropoint). The Barrier is not opened until the last thread in the group reaches the Barrier, and the previously blocked thread continues running. The process is shown below

Each of the three threads in the figure above has a barrier. Await, and any thread running to the barrier. Await will enter a blocking wait state until all three threads have reached the barrier.

How to use CyclicBarrier

The CyclicBarrier object is instantiated using its constructor to set the amount of data that the barrier is intercepting (the number of times the barrier. Await method is called). Each thread tells the CyclicBarrier that I have reached the barrier by calling the await method on the CyclicBarrier instance. And it blocks itself.

In addition, if a Runnable implementation is set when a CyclicBarrier is constructed, the last barrier. Await thread executes this method to do some preset work

Cyclicbarriers are often used in scenarios where multiple threads compute data and end up combining the results. For example, an Excel sheet records all the bank statements of the user in a quarter, and each sheet records the bank statements of the user in each month. When you want to count the bank statements of the user in the whole quarter, you can first use multi-threading to count the bank statements of each sheet. Use the results of each thread to calculate the user’s bank statement for the entire quarter.

Public class CyclicBarrierTest implements Runnable{/* Create a CyclicBarrier instance, set the barrier to 3, and execute the run method */ private CyclicBarrier cb = new CyclicBarrier(3,this); / * create a thread pool, only three months, so just three threads * / private Executor Executor. = Executors newFixedThreadPool (3); Private ConcurrentHashMap<String,Integer> sheetBankWaterCount = new ConcurrentHashMap<String, Integer>(); public voidcount() {
        for(int i = 0; i<3; I++){/* each thread is used to process tasks in a single sheet */ executor.execute(new)Runnable() {

                public void run() {/* SheetBankWaterCount.put (thread.currentThread ().getName(),1); Try {/* The thread calls await to set the barrier */ cb.await(); }catch (BrokenBarrierException e){ e.printStackTrace(); }catch (InterruptedException e){ e.printStackTrace(); }}}); }} /* Wait until all threads reach the barrier */ public voidrun() { int res = 0; /* Calculate the quarterly bank statements based on the results of the previous multithreading */for (Map.Entry<String,Integer> sheet: sheetBankWaterCount.entrySet()) {
            res += sheet.getValue();
        }

        sheetBankWaterCount.put("result",res); / / system.out.println (res); / / system.out.println (res); } public static void main(String[] args){ CyclicBarrierTesttest= new CyclicBarrierTest(); /* Notice that there is no need to call test.run(), the last await method calls the run method */ test.count(); }}Copy the code

3. Problems to be paid attention to when using CyclicBarrier

When using a CyclicBarrier in a thread pool, it is important to note that a deadlock occurs if the number of threads is greater than the number of blocked threads set up in a CyclicBarrier instance. The number of times the await() method is called must equal the number of blocked threads set in the barrier, otherwise it will also deadlock.

CyclicBarrier and CountDownLatch

  1. First of all, both can make one or more threads block waiting, and both can be used in coordination between multiple threads to play the role of thread synchronization. However, CountDownLatch triggers the time only after all the threads countDown, wakes the await thread on latch, and continues the work of its own thread after countDown. CyclicBarrier is a barrier that synchronizes all threads calling await methods until all methods have executed await methods.
  2. The CountDownLatch counter can only be used once, while the CyclicBarrier counter can be reset by calling the reset() method to handle more complex business scenarios.

Java concurrency CountDownLatch usage method

Semaphore Usage Guide for Concurrent Programming in Java