The Countdownlatch and Cyclicbarrier of Java concurrent programming

Source: Internet
Author: User

Countdownlatch and Cyclicbarrier are two of the most useful concurrency tool classes under the JDK concurrent package, and they provide a means to control the concurrency process. This article will provide some application scenarios, combined with the source code, their specific implementation and how to use a specific analysis.

Countdownlatch

Countdownlatch allows one or more threads to wait for another thread to complete the operation.

Countdownlatch Use Cases

Requirements : Parse a file under multiple TXT file data, you can consider the use of multi-threaded parallel parsing to improve resolution efficiency. Each thread parses the data in one file and waits until all the data has been parsed before doing anything else.

Design Analysis : In this requirement, it is necessary to implement the main thread to wait for all threads to complete the file parsing operation, Countdownlatch just can do.

Code Implementation :

Note: Only give a simple shelf, indicating the specific use of Countdownlatch, TXT file parsing here does not do the detailed code implementation.

    • Countdownlatch statement:
      The Countdownlatch constructor accepts the int parameter as its counter, and if it wants to wait for n points to complete, it passes N;
    • When calling Countdownlatch's Countdown method, the await method, where n reduces 1,countdownlatch, blocks the main thread until n is reduced to 0.
Countdownlatch Source Code Analysis

Countdownlatch is a custom Aqs synchronization component, followed by a custom Synchronizer Sync, countdown method, and await method as a pointcut to analyze the specific implementation of Countdownlatch.

    • Custom Synchronizer Sync Implementation

      Synchronizer Sync realizes the shared acquire and release of the synchronization state, the previous article has already introduced the AQS related content in detail, here I no longer do the detailed introduction analysis.

    • Construction method

      As can be seen from the concrete implementation of the construction method, the int parameter passed in by the constructor method count is actually the state of the Synchronizer.

    • Countdown implementation

      The whole countdown only do one thing, release the synchronization state, the actual meaning of the synchronization state here is the number of points that need to wait for completion, as long as each completion of a point, call the Countdown method to release the synchronization state.

    • Await implementation
      The Countdownlatch provides an await with a time-out and an await with no time-out:

      The essence of await is to obtain the synchronization state, the synchronization state = = 0 is established, the current wait for the completion of the point has been completed, the main thread continues to execute, otherwise, the main thread into the waiting queue spin wait until the state is released after the synchronization states = = 0. Sometimes the main thread is not always spin wait, this time with time-out await will come in handy, set the timeout time, if in the specified time n points are not completed, return false, the main thread no longer wait, continue to execute.

Summary: Countdownlatch is essentially a AQS counter that implements thread waits and wakes through Aqs.

Cyclicbarrier

Cyclicbarrier, let a group of threads reach a synchronization point and then continue running together, where any one of the threads does not reach the synchronization point, and the other arriving threads are blocked.

Cyclicbarrier Source Code Analysis
    • Construction method
      Cyclicbarrier provides two construction methods CyclicBarrier(int parties) and CyclicBarrier(int parties, Runnable barrierAction) :

      • Cyclicbarrier (int parties)
        The default constructor method, which represents the number of threads intercepted.

      • Cyclicbarrier (int parties, Runnable barrieraction)
        Because the schedule before the thread is determined by the CPU, the default construction method cannot set the thread execution priority, and Cyclicbarrier provides a more advanced constructor CyclicBarrier(int parties, Runnable barrierAction) that prioritizes thread barrieraction when threads arrive at the synchronization point. This makes it easier to handle some of the responsible business scenarios.

After the Cyclicbarrier is created, each thread calls the await method to tell Cyclicbarrier that it has reached the synchronization point, and then the current thread is blocked. Let's take a look at the concrete implementation of the await method.

    • Await implementation
      Cyclicbarrier also provides an await with a time-out and an await without a time-out:

      The core of the entire await method is the invocation of the Dowait method, and we take a look at the concrete implementation of dowait.

    • Dowait implementation

      1. In the first part of the dowait, the main completion is that when all the threads reach the synchronization point (barrier), all the waiting threads are woken up and run down together, and the prioritized thread can be determined according to the parameter barrieraction.

      2. In the latter half of dowait, when the thread does not reach the synchronization point (barrier), the thread enters the condition spin wait until the wait time-out or when all the threads arrive at barrier.

      Throughout the dowait:

      1. Use Reentrantlock to ensure thread safety for each operation;
      2. Thread wait/wake is implemented using lock mate condition;
      3. condition that the thread is awakened: Wait time out or all threads reach barrier.

So far, Cyclicbarrier's important realization of the source code analysis is over, and then still give a specific use case, to facilitate the mastery of cyclicbarrier specific usage.

Cyclicbarrier Use Cases

Requirements : Multi-threaded computing data, merge calculation results.

Code Implementation :

Operation Result:

Cyclicbarrier and Countdownlatch can all be thread-waiting, so what's the difference between the two?

The difference between Cyclicbarrier and Countdownlatch

Read all kinds of information and books, we all agree that the Countdownlatch is a counter, can only be used once, while the Cyclicbarrier counter provides the reset function, can be used multiple times. But I don't think that the difference between them is just that simple. Let's look at the purpose of the JDK author's design, as Javadoc describes them:

COUNTDOWNLATCH:A synchronization aid that allows one or more threads to wait until A set of operations being performed in Other threads completes.

CYCLICBARRIER:A synchronization aid that allows a set of threads to all wait for each other to reach A common barrier PO Int.

The description from Javadoc can be drawn as follows:

    • Countdownlatch: One or more threads, waiting for other threads to complete something before they can execute;
    • Cyclicbarrier: Multiple threads wait for each other until they reach the same synchronization point, and then continue to execute together.

For Countdownlatch, the focus is "one thread (multiple threads) waiting", while the other n threads can terminate or wait after completing "something". For Cyclicbarrier, the focus is on multiple threads, where any one thread is not completed and all threads must wait.

Countdownlatch is the counter, the thread completes a record one, but the count is not incremented but decrements, and Cyclicbarrier is more like a valve that requires all the threads to arrive before the valve can be opened and then continue execution.

The Countdownlatch and Cyclicbarrier of Java concurrent programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.