CyclicBarrier源码

CyclicBarrier是一种同步工具,它允许一组线程在到达一个公共的屏障点时阻塞等待,直到最后一个线程到达屏障点,屏障才能开启,此时所有被阻塞线程才能被唤醒从而继续执行。

首先要清楚的是CyclicBarrier主要是基于reentrantlock的条件等待

主要的成员变量和构造方法:
    /** The lock for guarding barrier entry */
    private final ReentrantLock lock = new ReentrantLock();
    /** Condition to wait on until tripped */
    private final Condition trip = lock.newCondition();
    /** The number of parties */
    private final int parties;
    /* The command to run when tripped */
    private final Runnable barrierCommand;
    /** The current generation */
    private Generation generation = new Generation();

    /**
     * Number of parties still waiting. Counts down from parties to 0
     * on each generation.  It is reset to parties on each new
     * generation or when broken.
     */
    private int count;

lock:排他锁,保证数据访问安全。

trip:与屏障相关的条件。

parties:屏障拦截的线程数,这个值是常量初始化后不再变化。

barrierCommand:在所有线程到达屏障点时优先执行的任务。

count:当前需要阻塞等待的线程数。

generation:线程的中断状态相关。Generation是一个静态内部类,这只有一个布尔类型的成员变量broken,broken表示线程的中断。

private static class Generation {
    boolean broken = false;
} 

所以构造方法:

public CyclicBarrier(int parties, Runnable barrierAction) {
    if (parties <= 0) throw new IllegalArgumentException();
    this.parties = parties;
    this.count = parties;//初始化等待数
    this.barrierCommand = barrierAction;//传入回调任务
}
    public CyclicBarrier(int parties) {
        this(parties, null);
    }
重要方法:

栅栏可以提供有时限的等待,同样是基于reentrantlock。

    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方法了:

 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();
        }
    }

其他的方法都是辅助方法,一目了然:

//开启下一代,这个方法是不允许外部调用的
    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();
    }

//重置栅栏,这个方法可能会抛出异常
    public void reset() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            breakBarrier();   // break the current generation
            nextGeneration(); // start a new generation
        } finally {
            lock.unlock();
        }
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值