概述

CyclicBarrier 是并发包中的一个工具类,它的典型应用场景为:几个线程执行完任务后,执行另一个线程(回调函数,可选),然后继续下一轮,如此往复。

打个通俗的比方,可以把 CyclicBarrier 的执行流程比作:几个人(类比线程)围着操场跑圈,所有人都到达终点后(终点可理解为“屏障(barrier)”,到达次序可能有先后,对应线程执行任务有快慢),执行某个操作(回调函数),然后再继续跑下一圈(下一次循环),如此往复。

该类与 CountDownLatch 相比,可以把后者理解为“一次性(one-shot)”操作,而前者是“可循环”的操作,下面分析其代码实现。

代码分析

CyclicBarrier 的主要方法如下:

其中常用的是两个 await 方法,作用是让当前线程进入等待状态。

成员变量及嵌套类:

// 内部嵌套类
private static class Generation {
boolean broken = false;
} /** 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;

内部嵌套类 Generation 表示代数,每次屏障(barrier)破坏之前属于同一代,之后进入下一代。

构造器

// 无回调函数
public CyclicBarrier(int parties) {
this(parties, null);
} // 有回调函数
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}

CyclicBarrier 有两个构造器,其中后者可以传入一个回调函数(barrierAction),parties 表示调用 await 的线程数。

await 方法

// 阻塞式等待
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));
}

可以看到两个 await 方法都是调用 dowait 方法来实现的(该方法也是 CyclicBarrier 的核心方法),如下:

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();
} // count 减 1
int index = --count;
if (index == 0) { // tripped
// count 减到 0 时触发的操作
boolean ranAction = false;
try {
// 传入的回调函数
final Runnable command = barrierCommand;
if (command != null)
// 若传了回调函数,则执行回调函数
// PS: 由此可知,回调函数由最后一个执行结束的线程执行
command.run();
ranAction = true;
// 进入下一代(下一轮操作)
nextGeneration();
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
} // loop until tripped, broken, interrupted, or timed out
for (;;) {
try {
// count 不为 0 时,当前线程进入等待状态
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();
}
}

nextGeneration 和 breakBarrier:

// 进入下一轮
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();
}

执行流程:初始化时 parties 和 count 的值相同(由构造器 parties 参数传入),之后每有一个线程调用 await 方法 count 值就减 1,直至 count 为 0 时(若不为 0 则等待),执行传入的回调函数 barrierCommand(若不为空),然后唤醒所有线程,并将 count 重置为 parties,开始下一轮操作。

场景举例

为了便于理解 CyclicBarrier 的用法,下面简单举例演示(仅供参考):

public class CyclicBarrierTest {
private static final int COUNT = 3; public static void main(String[] args) throws InterruptedException {
// 初始化 CyclicBarrier 对象及回调函数
CyclicBarrier cyclicBarrier = new CyclicBarrier(COUNT, () -> {
// 模拟回调函数的操作(模拟写操作)
System.out.println(Thread.currentThread().getName() + " start writing..");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("---------");
}); while (true) {
// 创建几个线程执行任务
for (int i = 0; i < COUNT; i++) {
new Thread(() -> {
// 模拟读操作
System.out.println(Thread.currentThread().getName() + " is reading..");
try {
TimeUnit.SECONDS.sleep(3);
// 等待
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
// 睡眠 10 秒,然后进入下一轮
TimeUnit.SECONDS.sleep(10);
}
}
} /* 执行结果(仅供参考):
Thread-0 is reading..
Thread-1 is reading..
Thread-2 is reading..
Thread-1 start writing..
---------
Thread-3 is reading..
Thread-4 is reading..
Thread-5 is reading..
Thread-5 start writing..
---------
*/

PS: 此处模拟多个线程执行读操作,都读完后再执行写操作;之后再读、再写……可以理解为简单的对账系统。

此处代码仅供参考,只为便于理解该类的用法。实际上每次创建线程是不合理的(可以使用线程池,由于未分析,这里暂不使用)。

小结

CyclicBarrier 也可以理解为倒数的计数器,它与 CountDownLatch 有些类似。后者是“一次性”的,而前者是“可循环使用”的

Stay hungry, stay foolish.

PS: 本文首发于微信公众号【WriteOnRead】。

【JDK】JDK源码分析-CyclicBarrier的更多相关文章

  1. JDK Collection 源码分析(2)—— List

    JDK List源码分析 List接口定义了有序集合(序列).在Collection的基础上,增加了可以通过下标索引访问,以及线性查找等功能. 整体类结构 1.AbstractList   该类作为L ...

  2. JDK AtomicInteger 源码分析

    @(JDK)[AtomicInteger] JDK AtomicInteger 源码分析 Unsafe 实例化 Unsafe在创建实例的时候,不能仅仅通过new Unsafe()或者Unsafe.ge ...

  3. 设计模式(十八)——观察者模式(JDK Observable源码分析)

    1 天气预报项目需求,具体要求如下: 1) 气象站可以将每天测量到的温度,湿度,气压等等以公告的形式发布出去(比如发布到自己的网站或第三方). 2) 需要设计开放型 API,便于其他第三方也能接入气象 ...

  4. JDK Collection 源码分析(3)—— Queue

    @(JDK)[Queue] JDK Queue Queue:队列接口,对于数据的存取,提供了两种方式,一种失败会抛出异常,另一种则返回null或者false.   抛出异常的接口:add,remove ...

  5. JDK Collection 源码分析(1)—— Collection

    JDK Collection   JDK Collection作为一个最顶层的接口(root interface),JDK并不提供该接口的直接实现,而是通过更加具体的子接口(sub interface ...

  6. 【JDK】JDK源码分析-AbstractQueuedSynchronizer(1)

    概述 前文「JDK源码分析-Lock&Condition」简要分析了 Lock 接口,它在 JDK 中的实现类主要是 ReentrantLock (可译为“重入锁”).ReentrantLoc ...

  7. JDK源码分析—— ArrayBlockingQueue 和 LinkedBlockingQueue

    JDK源码分析—— ArrayBlockingQueue 和 LinkedBlockingQueue 目的:本文通过分析JDK源码来对比ArrayBlockingQueue 和LinkedBlocki ...

  8. JDK 源码分析(4)—— HashMap/LinkedHashMap/Hashtable

    JDK 源码分析(4)-- HashMap/LinkedHashMap/Hashtable HashMap HashMap采用的是哈希算法+链表冲突解决,table的大小永远为2次幂,因为在初始化的时 ...

  9. JDK源码分析(11)之 BlockingQueue 相关

    本文将主要结合源码对 JDK 中的阻塞队列进行分析,并比较其各自的特点: 一.BlockingQueue 概述 说到阻塞队列想到的第一个应用场景可能就是生产者消费者模式了,如图所示: 根据上图所示,明 ...

随机推荐

  1. Python入门(一) 异常处理

    异常处理 捕捉异常可以使用try/except语句. try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理. 以下是语法: try: <语句> # ...

  2. 1.Solr安装与配置

    1.Solr安装 1:安装 Tomcat,解压缩即可. 2:解压 solr. 3:把 solr 下的dist目录solr-4.10.3.war部署到 Tomcat\webapps下(去掉版本号). 4 ...

  3. 嵊州D2T1 “我只是来打个电话”

    嵊州D2T1 “我只是来打个电话” 精神病院有一个这样的测试. 给出一个正整数集合,集合中的数各不相同,然后要求病人回答: 其中有多少个数,恰好等于集合中另外两个(不同的)数之和? 回答正确的人,即可 ...

  4. VUE-CLI3.0脚手架安装

    文档:https://cli.vuejs.org/zh/guide/ 条件: npm 更至最新 node >=8.9 1.全局安装 npm install -g @vue/cli 或 yarn ...

  5. c++学习书籍推荐《C++编程思想第一卷》下载

    百度云及其他网盘下载地址:点我 编辑推荐 <C++编程思想>(第1卷)(第2版)第1版荣获"软件开发"杂志评选的1996年度 图书震撼大奖,中文版自2000年推出以来, ...

  6. java三大集合遍历

    1. 场景描述 今天需要用到map集合遍历,一下子忘记咋写了,以前一般用map.get()直接获取值,很少遍历map,刚好总结下java中常用的几个集合-map,set,list遍历. 2. 解决方案 ...

  7. Specifying the Code to Run on a Thread

    This lesson shows you how to implement a Runnable class, which runs the code in its Runnable.run() m ...

  8. spark 源码分析之十五 -- Spark内存管理剖析

    本篇文章主要剖析Spark的内存管理体系. 在上篇文章 spark 源码分析之十四 -- broadcast 是如何实现的?中对存储相关的内容没有做过多的剖析,下面计划先剖析Spark的内存机制,进而 ...

  9. Golang 高效实践之defer、panic、recover实践

    前言 我们知道Golang处理异常是用error返回的方式,然后调用方根据error的值走不同的处理逻辑.但是,如果程序触发其他的严重异常,比如说数组越界,程序就要直接崩溃.Golang有没有一种异常 ...

  10. 我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3cp8ng15g94wc

    我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3cp8ng15g94wc