Java multithreaded Java multithreaded CyclicBarrier

Java multithreading (XIII) CyclicBarrier of Java multithreading

The    CyclicBarrier is very similar to CountDownLatch. It can also realize the technical waiting between threads, but its function is more complex and powerful than CountDownLatch. The main application scenarios are similar to CountDownLatch.

1.1 CyclicBarrier class

                                 , a tool class under the java.util.concurrent package, literally.

  • CyclicBarrier is a synchronization mechanism that enables a group of threads to wait at the same obstacle point.
  • CyclicBarriers can be reused by resetting the counters.
  • CyclicBarrier supports an optional Runnable command (instantiating parameters in the constructor), which is executed after the last thread arrives, but before any thread is released. This command is executed only once at the barrier and is completed by the last thread to arrive. This barrier behavior is useful for updating the shared state before either party continues.
  • All or none breakage model: if a thread leaves the barrier point prematurely due to interruption (or failure of execution process, timeout, etc.), all other threads waiting at the barrier point will leave the barrier at the same time because of broken barrier exception or InterruptedException exception.
    Memory consistency impact:
    1. The behavior of a thread before calling the await() method takes precedence over any behavior in the barrier action.
    1. The successful return of barrier action takes precedence over all other wait for thread await().

1.2 CyclicBarrier example

package com.yuanxw.chapter13;

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

/**
 * CyclicBarrier It literally means a recyclable Barrier.
 * What it has to do is to let a group of threads get blocked when they reach a barrier (also known as synchronization point), and the barrier will not open until the last thread reaches the barrier, and all threads blocked by the barrier will continue to work.
 * CyclicBarrier The default construction method is CyclicBarrier(int parties), whose parameters represent the number of threads blocked by the barrier. Each thread calls the await method to tell CyclicBarrier that I have reached the barrier, and then the current thread is blocked.
 */
public class CyclicBarrierExample {

    private static volatile boolean isRunning = true;
    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new Runnable() {
            @Override
            public void run() {
                isRunning = false;
                System.out.println("After task execution, callback function!!!");
            }
        });

        /** Thread -A **/
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(20);
                System.out.println(String.format("Thread [%s]Execution completed", Thread.currentThread().getName()));
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        },"Thread-A").start();

        /** Thread -A **/
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(10);
                System.out.println(String.format("Thread [%s]Execution completed", Thread.currentThread().getName()));
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        },"Thread-B").start();

        while (isRunning) {
            System.out.println(String.format("Currently waiting quantity:[%s]", cyclicBarrier.getNumberWaiting()));
            System.out.println(String.format("Waiting for required quantity:[%s] ", cyclicBarrier.getParties()));
            System.out.println(String.format("Interrupt or timeout:[%s]", cyclicBarrier.isBroken()));
            TimeUnit.SECONDS.sleep(5);
        }
    }
}

Execution result:

Currently waiting quantity: [0]
Waiting for required quantity: [2] 
Interrupt or timeout: [false]
Currently waiting quantity: [0]
Waiting for required quantity: [2] 
Interrupt or timeout: [false]
Thread B execution completed
 Currently waiting quantity: [1]
Waiting for required quantity: [2] 
Interrupt or timeout: [false]
Currently waiting quantity: [1]
Waiting for required quantity: [2] 
Interrupt or timeout: [false]
Thread-A execution completed
 After task execution, callback function!!!

1.3 differences between cyclicbarrier and CountDownLatch

  1. CountDownLatch is a counter that can only be used once, while the counter of CyclicBarrier provides reset function and can be used multiple times.
  2. For CountDownLatch, the focus is "one thread (multiple threads) waiting", while other N threads can terminate or wait after completing "something". For CyclicBarrier, the focus is on multiple threads. If any thread fails to complete, all threads must wait.
  3. CountDownLatch is a counter. A thread completes one record, but the count is not increasing but decreasing. The CyclicBarrier is more like a valve, which needs all threads to arrive before the valve can be opened and then continue to execute.

                           . Thank you for your attention.

——Yunxw

104 original articles published, 161 praised, 460000 visitors+
His message board follow

Tags: Java

Posted on Wed, 15 Jan 2020 06:05:10 -0500 by nick_whitmarsh