How to apply CyclicBarrier cycle barrier in Java
May 12, 2023 pm 02:19 PM1. Introduction
CyclicBarrier literally means loop barrier (cyclic barrier). It can make a group of threads wait for a certain state (barrier point) and then execute them all at the same time. It is called loopback because CyclicBarrier can be reused after all waiting threads are released.
The function of CyclicBarrier is to make a group of threads wait for each other. When a common point is reached, all previously waiting threads will continue to execute, and the CyclicBarrier function can be reused.
2. Use of CyclicBarrier
Construction method:
// parties表示屏障攔截的線程數(shù)量,每個線程調(diào)用 await 方法告訴 CyclicBarrier 我已經(jīng)到達了屏障,然后當前線程被阻塞。 public CyclicBarrier(int parties) // 用于在線程到達屏障時,優(yōu)先執(zhí)行 barrierAction,方便處理更復雜的業(yè)務場景(該線程的執(zhí)行時機是在到達屏障之后再執(zhí)行)
Important method:
//屏障 指定數(shù)量的線程全部調(diào)用await()方法時,這些線程不再阻塞 // BrokenBarrierException 表示柵欄已經(jīng)被破壞,破壞的原因可能是其中一個線程 await() 時被中斷或者超時 public int await() throws InterruptedException, BrokenBarrierException public int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException //循環(huán) 通過reset()方法可以進行重置
CyclicBarrier Application Scenario
Using CyclicBarrier can be used in scenarios where multi-threaded data is calculated and the calculation results are finally merged.
Using the feature of CyclicBarrier that the counter can be reset and the barrier can be reused, it can support scenarios similar to "full departure"
Simulation Merged calculation scenario
Using CyclicBarrier can be used to calculate data in multiple threads and finally merge the calculation results.
public class CyclicBarrierTest2 { //保存每個學生的平均成績 private Conc urrentHashMap<String, Integer> map=new ConcurrentHashMap<String,Integer>(); private ExecutorService threadPool= Executors.newFixedThreadPool(3); private CyclicBarrier cb=new CyclicBarrier(3,()->{ int result=0; Set<String> set = map.keySet(); for(String s:set){ result+=map.get(s); } System.out.println("三人平均成績?yōu)?"+(result/3)+"分"); }); public void count(){ for(int i=0;i<3;i++){ threadPool.execute(new Runnable(){ @Override public void run() { //獲取學生平均成績 int score=(int)(Math.random()*40+60); map.put(Thread.currentThread().getName(), score); System.out.println(Thread.currentThread().getName() +"同學的平均成績?yōu)椋?quot;+score); try { //執(zhí)行完運行await(),等待所有學生平均成績都計算完畢 cb.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } }); } } public static void main(String[] args) { CyclicBarrierTest2 cb=new CyclicBarrierTest2(); cb.count(); } }
Simulate the scene of "the bus is full of people"
Using the characteristics of CyclicBarrier's counter can be reset and the barrier can be reused, it can support scenes similar to "the bus is full of people"
public class CyclicBarrierTest3 { public static void main(String[] args) { AtomicInteger counter = new AtomicInteger(); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 5, 5, 1000, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), (r) -> new Thread(r, counter.addAndGet(1) + " 號 "), new ThreadPoolExecutor.AbortPolicy()); CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> System.out.println("裁判:比賽開始~~")); for (int i = 0; i < 10; i++) { threadPoolExecutor.submit(new Runner(cyclicBarrier)); } } static class Runner extends Thread{ private CyclicBarrier cyclicBarrier; public Runner (CyclicBarrier cyclicBarrier) { this.cyclicBarrier = cyclicBarrier; } @Override public void run() { try { int sleepMills = ThreadLocalRandom.current().nextInt(1000); Thread.sleep(sleepMills); System.out.println(Thread.currentThread().getName() + " 選手已就位, 準備共用時: " + sleepMills + "ms" + cyclicBarrier.getNumberWaiting()); cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); }catch(BrokenBarrierException e){ e.printStackTrace(); } } } }
Output result:
Player No. 3 is in place, ready to share: 78ms0
3. CyclicBarrier source code analysis
Player No. 1 is in place, ready to share: 395ms1## Player No. 5 is in position, ready to share: 733ms2 Player No. 2 is in position, ready to share: 776ms Player No. 3
is in position, ready to share: 807ms4
Referee: The game has started ~~
4 players are in place, ready to share: 131ms0
3 players are in place, ready to share: 256ms1
2 players are in place, ready to share: 291ms2
Player No. 1 is in place, ready to share: 588ms3
Player No. 5 is in place, ready to share: 763ms4
Referee: The game begins~~
CyclicBarrier process
The main process is:
- Acquire the lock and enter blocking if count != 0;
- Before entering blocking, you first need to enter the condition queue, then release the lock, and finally block;
- If count != 0, a wake-up will be performed. All nodes in the condition queue are converted into blocking queues;
- After being awakened, the lock will be acquired. If the lock acquisition fails, it will enter the lock blocking queue;
- If the lock is acquired successfully, the lock is released, and the threads in the synchronization queue are awakened.
#A few common questions?
- 1. A group of threads wait for each other before triggering the barrier. How is the wake-up logic implemented after the last thread reaches the barrier. The wake-up process is by calling
- java.util. concurrent.locks.Condition#signalAll
Wake up all nodes on the condition queue.
2. How is column deletion cycle implemented? In fact, the condition queue and blocking queue of a mutex ReentrantLock are converted. - 3. Implementation logic of conversion from condition queue to synchronization queue? During the conversion process, all blocked threads in the condition queue will first be awakened, and then the lock will be acquired. If the acquisition fails, Enter the synchronization queue.
- The difference between CyclicBarrier and CountDownLatch
- The counter of CountDownLatch can only be used once, while the counter of CyclicBarrier can be reset using the reset() method. Therefore, CyclicBarrier can handle more complex business scenarios. For example, if a calculation error occurs, the counter can be reset and the threads can be re-executed.
- CyclicBarrier also provides getNumberWaiting (which can obtain CyclicBarrier blocking the number of threads), isBroken (used to know whether the blocked thread has been interrupted) and other methods.
- CountDownLatch will block the main thread, CyclicBarrier will not block the main thread, only the child thread.
- Both CountDownLatch and CyclicBarrier can realize waiting between threads, but they have different focuses. CountDownLatch is generally used for one or more threads to wait for other threads to complete their tasks before executing them. CyclicBarrier is generally used for a group of threads to wait for each other to reach a certain state, and then the group of threads execute at the same time.
- CyclicBarrier can also provide a barrierAction to merge multi-threaded calculation results.
CyclicBarrier implements the blocking and awakening of a group of threads through ReentrantLock's "exclusive lock" and Conditon, while CountDownLatch is implemented through the "shared lock" of AQS
The above is the detailed content of How to apply CyclicBarrier cycle barrier in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear
