Barrier is a frequently used synchronization tool in multi-threaded programming. It is especially used for synchronization in the computing process of large data volumes. This article takes the Barrier Implementation of the concurrent toolkit of Doug Lea, which is widely used as an example to discuss it. In Doug Lea's concurrent toolkit, Barrier is an interface that provides two Barrier implementations in the concurrent package: javasicbarrier and Rendezvous. The following is the definition of the Barrier interface:
- Public InterfaceBarrier {
- /**
- * Return the number of parties that must meet per barrier
- * Point. The number of parties is always at least 1.
- **/
- Public IntParties ();
- /**
- * Returns true if the barrier has been compromised
- * By threads leaving the barrier before a synchronization
- * Point (normally due to interruption or timeout ).
- * Barrier methods in implementation classes throw
- * Throw BrokenBarrierException upon detection of breakage.
- * Implementations may also support some means
- * To clear this status.
- **/
- Public BooleanBroken ();
- }
The method in the Barrier interface is very simple. parties () returns the number of threads to be synchronized at the Barrier. broken () returns a flag indicating whether the release has been destroyed. The Barrier interface does not provide a Barrier method, but is provided in the Barrier Implementation of c and Rendezvous. You may wonder why these methods are not provided in the Barrier interface? Because of the differences in these implementations, it is difficult to extract a shared method signature from these implementations. For example, the method for adding javasicbarrier to a barrier (),
- // Javasicbarrier. java
- Public IntBarrier ()Throws InterruptedException, BrokenBarrierException {
- ReturnDoBarrier (False, 0 );
- }
- Protected Synchronized IntDoBarrier (BooleanTimed,LongMsecs)
- Throws InterruptedException, TimeoutException, BrokenBarrierException {
- IntIndex = -- count _;
- If(Broken _){
- Throw NewBrokenBarrierException (index );
- }
- Else If(Thread. Interrupted ()){
- Broken _ =True;
- Policyall ();
- Throw New InterruptedException();
- }
- Else If(Index = 0 ){// Tripped
- Count _ = parties _;
- ++ Resets _;
- Policyall ();
- Try{
- If(BarrierCommand _! =Null)
- BarrierCommand _. run ();
- Return0;
- }
- Catch(RuntimeExceptionEx ){
- Broken _ =True;
- Return0;
- }
- }
- Else If(Timed & msecs <= 0 ){
- Broken _ =True;
- Policyall ();
- Throw NewTimeoutException (msecs );
- }
- Else{// Wait until next reset
- IntR = resets _;
- LongStartTime = (timed )?System. CurrentTimeMillis (): 0;
- LongWaitTime = msecs;
- For(;;){
- Try{
- & N