SoFunction
Updated on 2025-04-12

What is Java's CyclicBarrier (code example)

Your answer (colloquial, interview scenario)
Interviewer: What is JavaCyclicBarrier
you:
OK, let me give you an example. For example, a game requires all 5 players to be ready before it can start, and you can use it at this time.CyclicBarrier

Core role
CyclicBarrierLet a group of threads wait for each other until all threads reach the barrier point (Barrier), and then continue to execute together. It is like a level, and you have to wait until all threads arrive before you can release it.

Core features

  • Reusable: After all threads pass through the barrier,CyclicBarrierIt will be automatically reset (for example, after the player ends one game, he can start the next game).
  • Support callbacks: You can set a callback task (Runnable) that triggers after all threads reach the barrier (such as sending broadcasts at the beginning of the game).
  • Use scenarios
  • Phase-based tasks: Multi-threads process data in batches, wait for all threads to complete the first stage, and then enter the second stage in a unified manner.
  • Pressure test simulation: Simulates 1,000 users to initiate requests at the same time (triggered at the same time after all threads are ready).
  • Distributed collaboration: After multiple microservice nodes are initialized, they provide services to the outside world at the same time.

Code Example

// 3 threads wait for each other, and execute callbacks after all arriveCyclicBarrier barrier = new CyclicBarrier(3, () -> {  
    ("All players are in place, the game begins!");  
});  
// Player thread(() -> {  
    ("Player A is ready to complete");  
    ();  // Wait for other players    ("Player A starts the game");  
});  
// Submit players similarlyB、CThreads  

Compare CountDownLatch

  • Reset capability:CyclicBarrierReusable,CountDownLatchOnly available at one time.
  • Trigger role:CyclicBarrierIt is threads waiting for each other.CountDownLatchIt is the main thread waiting for the child thread.

Predict the interviewer's possible questions and answers
Question 1: If a thread is inawait()What happens if it is interrupted?
answer:

  • The interrupted thread will be thrownInterruptedException, and other waiting threads will receiveBrokenBarrierException, the barrier will fail.
  • Need to callreset()You can only continue to use after resetting the barrier.

Question 2:CyclicBarrierHow is the underlying layer implemented?
answer:

  • based onReentrantLockandCondition
    • Maintain a counter internally and thread callsawait() Time counter decrement1。
    • When the counter is zeroed, the callback task is triggered and all waiting threads are awakened.

Knowledge framework and underlying principles supplement

Core mechanism
| Components | Functions |
|---------------------|-------------------------------------------------------------------------|
| Barrier | The location where the thread must wait for other threads to arrive. |
| Generation | Record the status of the current barrier (whether it has been broken), and supports reset and reuse. |
| Callback Task | OptionalRunnable, executed by the last thread that reaches the barrier. |

Source code-level implementation logic

Initialization: Set the number of participating threads (parties) and callback tasks.

await() process:

  • Get the lock (ReentrantLock), check if the barrier is damaged (Broken)。
  • Reduce the remaining count (count),likecount == 0, execute callbacks and wake all threads.
  • If it is not reset to zero, the thread passes()Enter the waiting queue.

Notes on using

  • Get the lock (ReentrantLock), check if the barrier is damaged (Broken)。
  • Reduce the remaining count (count),likecount == 0, execute callbacks and wake all threads.
  • If it is not reset to zero, the thread passes()Enter the waiting queue.

Practical cases

  • Scenario: During the e-commerce promotion, sales volumes in each region are counted and summarized.
  • plan:

CreateCyclicBarrier, the number of threads is the same as the number of regions.

Each thread calculates the sales volume of one area and calls it after completionawait()

After all threads arrive, the callback task is triggered to summarize the sales volume.

CyclicBarrier barrier = new CyclicBarrier(4, () -> {  
    ("The sales volume of all regions is calculated, and the total sales volume is:" + total);  
});  
// 4 areas of calculation threadsfor (int i = 0; i < 4; i++) {  
    (() -> {  
        calculateRegionSales();  
        ();  
    });  
}  

Summarize

  • CyclicBarrier is a powerful tool for multi-threading collaboration, suitable for scenarios that require multiple synchronizations (such as phased tasks).
  • Understand the underlying locking mechanism and exception handling to avoid barrier failure due to thread interruption.
  • Scenarios that take precedence over CountDownLatch: synchronization points need to be triggered repeatedly, or callback tasks need to be processed uniformly.

This is all about this article about what Java's CyclicBarrier is. For more information about Java's CyclicBarrier, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!