谈论高并发(三十)解析java.util.concurrent各种组件(十二) 认识CyclicBarrier栅栏

时间:2021-03-30 22:06:57

这次谈话CyclicBarrier栅栏,如可以从它的名字可以看出,它是可重复使用。

它的功能和CountDownLatch类别似,也让一组线程等待,然后开始往下跑起来。但也有在两者之间有一些差别

1. 不同的对象等。CountDownLatch组线程等待的是一个事件。或者说是一个计数器归0的事件。而CyclicBarrier等待的对象是线程,仅仅有线程都到齐了才往下运行

2. 使用方式不同,这个也是由等待的对象不同引起的,CountDownLatch须要调用await()来让线程等待。调用countDown()来改动状态,直到触发状态为0的事件。而CyclicBarrier仅仅须要调用await()让线程等待,当调用await()方法的线程数满足条件。就自己主动唤醒全部线程往下运行

3. CyclicBarrier能够自己主动循环使用,当一次拦截被打开后,会自己主动创建下一个拦截。CountDownLatch的计数器归0后不能再次使用

4. 底层实现不同,CountDownLatch使用AQS来实现底层同步,CyclicBarrier基于更上层的ReetrantLock + Condition条件队列实现

5. 失效机制不同,在CountDownLatch等待的线程假设被中断或者超时取消,不会影响其它线程。而CyclicBarrier採用all-or-none的机制,要么所有不通过,要么所有都通过。也就是说一旦在CyclicBarrier等待的线程有一个被中断或者超时取消,那么其它所有在这个CyclicBarrier等待的线程都被唤醒,通过栅栏往下运行

6. CyclicBarrier支持线程所有通过之后的回调功能,通过传入一个Runnable对象。由最后一个到达的线程来运行。而CountDownLatch不支持回调机制


以下看看CyclicBarrier的源码,它有一个内部类Generation来处理循环使用的问题,维护了一个broker状态表示当前的栅栏是否失效。假设失效,能够重置栅栏的状态。

当栅栏被打破时,就设置当前generation的broker为true表示失效,并唤醒全部等待的线程,即all-or-none机制

private static class Generation {
        boolean broken = false;
    }

private void nextGeneration() {
        // signal completion of last generation
        trip.signalAll();
        // set up next generation
        count = parties;
        generation = new Generation();
    }

private void breakBarrier() {
        generation.broken = true;
        count = parties;
        trip.signalAll();
    }


维护了一个ReentrantLock来作同步。并创建了一个相关的条件队列Condition,使用Condition的await()方法让线程在同一个条件队列等待。使用Condition.signalAll()唤醒全部在通过一条件队列等待的线程。

/** The lock for guarding barrier entry */
    private final ReentrantLock lock = new ReentrantLock();
    /** Condition to wait on until tripped */
    private final Condition trip = lock.newCondition();

维护了一个Runnable引用来支持回调功能

/* The command to run when tripped */
    private final Runnable barrierCommand;

public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }

维护了一个count来计数,当await()方法被调用一次, count就减1,直到count为0打开栅栏。

private int count;

能够看到CyclicBarrier的实例属性都没有使用volatile变量。那它怎么保证状态的可见性呢?CyclicBarrier使用了加显式锁的方式。我们知道显式锁和内置锁一样,都保证了可见性,有序性和原子性。

1. 进入锁相当于读volatile,会清空CPU缓存,强制从内存读取

2. 离开锁相当于写volatile,会把CPU写缓冲区的数据强制刷新到内存


CyclicBarrier经常使用支持普通的等待和限时的等待。最后都是落到了dowait()方法。

public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen;
        }
    }

public int await(long timeout, TimeUnit unit)
        throws InterruptedException,
               BrokenBarrierException,
               TimeoutException {
        return dowait(true, unit.toNanos(timeout));
    }

来看看dowait方法

1. 必须先获取锁,保证了可见性,有序性,原子性

2. 推断当前栅栏的状态,假设已经失效,抛出BrokerBarrierException异常

3. 假设线程被中断。那么让栅栏失效,会唤醒全部等待线程往下运行

4. 运行一次dowait就对count减一,用index记录下当前线程运行是的count值作为索引

5. 假设index == 0表示是最后到达的线程,能够打开栅栏了。首先假设有回调。就运行回调。然后重置栅栏状态,使之能够循环使用,返回0

6. 假设index不为0,表示不是最后到达的线程,就轮询等待,这里支持了限时操作,使用了Condition条件队列的await()机制。直到超时或者栅栏被正常失效。栅栏失效后会使用Condition来唤醒全部在同一个条件队列等待的线程。

private int dowait(boolean timed, long nanos)
        throws InterruptedException, BrokenBarrierException,
               TimeoutException {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            final Generation g = generation;

            if (g.broken)
                throw new BrokenBarrierException();

            if (Thread.interrupted()) {
                breakBarrier();
                throw new InterruptedException();
            }

           int index = --count;
           if (index == 0) {  // tripped
               boolean ranAction = false;
               try {
                   final Runnable command = barrierCommand;
                   if (command != null)
                       command.run();
                   ranAction = true;
                   nextGeneration();
                   return 0;
               } finally {
                   if (!ranAction)
                       breakBarrier();
               }
           }

            // loop until tripped, broken, interrupted, or timed out
            for (;;) {
                try {
                    if (!timed)
                        trip.await();
                    else if (nanos > 0L)
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    if (g == generation && ! g.broken) {
                        breakBarrier();
                        throw ie;
                    } else {
                        // We're about to finish waiting even if we had not
                        // been interrupted, so this interrupt is deemed to
                        // "belong" to subsequent execution.
                        Thread.currentThread().interrupt();
                    }
                }

                if (g.broken)
                    throw new BrokenBarrierException();

                if (g != generation)
                    return index;

                if (timed && nanos <= 0L) {
                    breakBarrier();
                    throw new TimeoutException();
                }
            }
        } finally {
            lock.unlock();
        }
    }

以下使用一个測试用例来測试CyclicBarrier的功能

1. 创建一个5个容量的CyclicBarrier,并设置回调

2. 执行12个线程

package com.lock.test;

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierUsecase {
	private CyclicBarrier barrier = new CyclicBarrier(5, new Runnable(){

		@Override
		public void run() {
			System.out.println("Callback is running");
		}
		
		
	});
	
	public void race() throws Exception{
		System.out.println("Thread " + Thread.currentThread().getName() + " is waiting the resource");
		barrier.await();
		System.out.println("Thread " + Thread.currentThread().getName() + " got the resource");
	}
	
	public static void main(String[] args){
		final CyclicBarrierUsecase usecase = new CyclicBarrierUsecase();
		
		for(int i = 0; i < 12; i++){
			Thread t = new Thread(new Runnable(){

				@Override
				public void run() {
					try {
						usecase.race();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}, String.valueOf(i));
			t.start();
		}
	}
}

測试结果:

1. 能够看到5个线程在等待。直到满5个线程到达之后打开栅栏,这5个线程往下运行,并运行回调

2. 栅栏被循环使用了。又有5个线程等待。直到满5个线程到达又打开栅栏往下运行。并运行回调

3. 栅栏又被循环使用,可是仅仅有2个线程,不满5个,就一直等待

Thread 0 is waiting the resource
Thread 4 is waiting the resource
Thread 5 is waiting the resource
Thread 3 is waiting the resource
Thread 2 is waiting the resource
Callback is running
Thread 1 is waiting the resource
Thread 0 got the resource
Thread 2 got the resource
Thread 6 is waiting the resource
Thread 7 is waiting the resource
Thread 4 got the resource
Thread 9 is waiting the resource
Thread 8 is waiting the resource
Thread 3 got the resource
Thread 5 got the resource
Callback is running
Thread 8 got the resource
Thread 1 got the resource
Thread 7 got the resource
Thread 6 got the resource
Thread 10 is waiting the resource
Thread 11 is waiting the resource
Thread 9 got the resource

版权声明:本文博客原创文章。博客,未经同意,不得转载。