What is a CyclicBarrier?
Loop fence – literally loop fence – allows a group of threads to wait until a state is reached before they all execute simultaneously. Cyclicbarriers are called loops because they can be reused once all the waiting threads have been released. Called the fence, is to describe all threads blocked by the fence, when all reached, jump the fence together to execute, also considered image. We can call this state a barrier.
How do cyclicbarriers work and are used?
If you look at the API CyclicBarrier, there are two constructors
public CyclicBarrier(int parties)
public CyclicBarrier(int parties, Runnable barrierAction)
Copy the code
The first parameter indicates the number of threads that execute together. The second argument represents the first thread to execute before all threads within the barrier are executed together. The method await() to keep threads in the barrier state
public int await(a)
public int await(long timeout, TimeUnit unit)
Copy the code
The first default method, which waits until all threads are in the barrier state before executing the second method, specifies how long to wait. When all threads are not in the barrier state, the thread continues to execute.
Example of CyclicBarrier application scenario
Take a package tour as an example. Before departure, the tour guide will receive the passport and visa at the airport and handle the collective exit formalities. Therefore, it is necessary to wait for everyone to arrive before departure, and then send the passport and visa to everyone. Corresponding to CyclicBarrier. Everyone enters the barrier state when they arrive. When they all arrive, arouse everyone to set off for the journey. Before the trip, the tour guide will issue passports and visas.
Different from CountDownLatch?
CountDownLatch can only be used once, while CyclicBarrier can be used repeatedly. For example, in multi-threaded computation, a more reasonable number of threads can be set. At the same time, each thread only needs to handle reasonable computation tasks without worrying about memory overflow, reducing the performance cost caused by thread context switching. It’s like running in small steps. CountDownLatch is implemented based on AQS sharing mode. CyclicBarrier is implemented based on Condition. The CountDownLatch count is controlled by the user, and the CyclicBarrier count is controlled by itself. CyclicBarrier is cyclic, so multi-task calculation can achieve a cumulative change in the result of a process, rather than only a constant final result.