Java Concurrency Basics CyclicBarrier Analysis!

Mondo Technology Updated on 2024-02-02

List of high-quality authors

J**A Concurrency Basics: Comprehensive Analysis of CyclicBarrier! - The advantage of CyclicBarrier is that it realizes mutual waiting and collaboration between threads, ensuring that all threads can continue to execute only after reaching a predetermined barrier point, it supports the reuse of barriers, which is very suitable for multi-turn task synchronization, in addition, CyclicBarrier also allows specific operations to be performed at the barrier point, which provides convenience for complex multi-threaded collaboration.

cyclicbarrierAllows a group of threads to wait for each other until all threads reach a certain barrier point, and then these threads can continue to perform subsequent tasks, which can be recycled, that is, when all threads have reached the barrier point, the barrier will automatically reset and wait for the next round of threads to arrive.

Let's take an example in real business: Suppose there is a large e-commerce company that needs to carry out a lot of product data pre-processing work during the annual "Double 11" promotion to cope with the upcoming shopping peak. This pre-processing work includes many steps, such as the verification of product information, inventory updates, adjustments, etc., due to the huge amount of data, the company decided to use a multi-threaded approach to speed up the processing process.

A company can divide the entire preprocessing task into multiple subtasks, each of which is completed by a separate thread, but there are certain dependencies between these subtasks, such as the need for one subtask to wait for other subtasks to complete before it can be executed.

It can be used in this type of scenariocyclicbarrierTo implement the wait between multiple threads, you can set the end point of each subtask as a barrier point, when all the subtasks are completed and reach this barrier point, it means that the first stage of the entire preprocessing work has been completed, and the second stage of the task can be started, and then,cyclicbarrierIt will automatically reset and wait for the next round of threads to arrive.

This ensures that tasks at each stage are executed in a predetermined order, while taking advantage of the benefits of multithreading to improve processing efficiency.

cyclicbarrierLocated inj**a.util.concurrentpackages, which are commonly used to solve the following types of technical problems:

Thread synchronization: When multiple threads need to perform certain operations at the same time, and those operations need to be ready before they can begincyclicbarrierIt can be used to synchronize these threads, and it allows a group of threads to wait at a certain point until all threads reach that point, and then the threads can continue to execute. Resource decomposition and task division: When processing large amounts of data or performing complex tasks, the task is often broken down into multiple subtasks, which are processed in parallel by different threadscyclicbarrierIt can ensure that no thread will advance to the next processing stage before all subtasks are completed, thus ensuring the consistency of data and the order of tasks. Recycling: withcountdownlatchDifferent,cyclicbarrierIt is reusable, and once all threads have reached the barrier point, the barrier is automatically reset so that it can be used for multiple rounds of task synchronization. Exception handlingcyclicbarrierIt also provides a feature that when a thread is waiting at the barrier point, if one thread is interrupted due to an exception, it can propagate the exception to other waiting threads, so that all threads can respond to the exception. Collaboration between threads: In some scenarios, threads need to work closely with each other, for example, multiple consumer threads in the producer-consumer pattern need to wait for all producer threads to complete production before they can start consumptioncyclicbarrierIt can provide a centralized synchronization point, simplifying the logic of collaboration between threads. Official Documentation:

Here's a usecyclicbarrierA simple example that simulates a multi-threaded task where each thread represents a worker who needs to complete their respective part of the work and then wait for the other workers to finish their work at a barrier point, and once all the workers have done their work, they will work together on the next phase of work, as in the following example:

import j**a.util.concurrent.brokenbarrierexception; 

import j**a.util.concurrent.cyclicbarrier;

public class cyclicbarrierexample catch (interruptedexception | brokenbarrierexception e)

system.out.println("workers" + thread.currentthread().getid() "Start the next phase of work");

.start();

In ** above,cyclicbarrierIt is set to wait for all 5 threads (workers) to be ready, and after each thread starts, a message is printed to indicate that it is ready, and then calledcyclicbarrier.await()The method goes into a wait state only when all threads have called itawait()method, they will continue with the next message to indicate the start of the next phase of work.

The output is as follows:

Worker 1 is ready

Worker 10 is ready

Worker 9 is ready

Worker 8 is ready

Worker 11 is ready

Worker 8 begins the next stage of work

Worker 10 begins the next stage of work

Worker 9 begins the next stage of work

Worker 11 began the next stage of work

Worker 1 begins the next stage of work.

Here's howcyclicbarrierThe meaning of some of the main methods:

cyclicbarrier(int parties), construct a method, and create a new onecyclicbarrierinstance, and set the number of threads that need to wait (that is, the number of parties).partiesIndicates the number of threads that need to wait when so many threads are calledawait()method, the barrier opens to allow the thread to continue executing. cyclicbarrier(int parties, runnable barrieraction), the constructor, in addition to setting the number of threads that need to wait, specifies a task to be executed when all threads have reached the barrier point (i.e., the barrier operation).barrieractionis onerunnableobject, it'srun()The method is called by a single thread after all threads have reached the barrier pointbarrieractionIt will only run once at the current barrier point, and if the barrier is reset, it will not be performed again the next time all threads arrive. int await() throws interruptedexception, brokenbarrierexception, this method is used to have the current thread wait at the barrier point until all threads reach this barrier point, if the current thread is not the last thread to reach the barrier point, then it will be blocked until all threads have arrived, if the current thread is the last to arrive, and it is specified in the constructorbarrieraction, then the operation is performed by the current thread or another thread (depending on the implementation), if the thread is interrupted during the wait, or the barrier is broken by another thread (by callingreset()method), then this method will throw an exception, and the return value is the order of arrival of the current thread that reached the barrier point, but this feature is rarely used in practical applications. int await(long timeout, timeunit unit) throws interruptedexception, brokenbarrierexception, timeoutexception, this method is the same as the previous oneawait()The method is similar, but allows you to specify a maximum wait time, and if all threads have reached the barrier point within the specified time, then the behavior is the sameawait()Again, if all threads have not arrived after the specified time, then this method will throwtimeoutexceptionint getparties(), return incyclicbarrierThe number of threads that need to wait. int getnumberwaiting()to return the number of threads currently waiting at the barrier point. boolean isbroken()if the barrier is broken (perhaps because a thread was interrupted while waiting, or calledbreakbarrier()method), then this method returnstruevoid reset()to reset the barrier to its initial state. This causes all threads that are currently waiting at the barrier point to be thrownbrokenbarrierexception, and the barrier can be reused. Note:cyclicbarrierIt is used to make a fixed number of threads wait for each other, not to synchronously access a shared resource, for synchronous access to a shared resource, other synchronization tools should be used, such assynchronizedkeywordlockImplementations of interfaces (egreentrantlock), or concurrent collections, etc.

J**A Concurrency Basics: Comprehensive Analysis of CyclicBarrier! - Programmer Goode Cyclicbarrier is a concurrency utility class in J**A that allows a group of threads to wait for each other until all threads reach a certain barrier point, and then those threads can continue to execute.

Pros:

It can be reused, making it ideal for multi-round task synchronization. Provides a mechanism for collaboration between threads to ensure that tasks are completed in stages. Barrier point operations can be specified to be performed automatically when all threads arrive. Cons:

If a thread is interrupted or canceled while waiting, it can cause a BrokenBarrierException. It is not suitable for synchronous access to shared resources, but more for task division and synchronization point control.

Follow me and learn Internet programming techniques every day - programmer Goode end!

Related Pages