博客
关于我
CyclicBarrier源码探究 (JDK 1.8)
阅读量:408 次
发布时间:2019-03-06

本文共 2967 字,大约阅读时间需要 9 分钟。

CyclicBarrier详解:从实现到使用技巧

1. 相关字段

CyclicBarrier(回环栅栏)通过以下字段实现线程安全:

  • ReentrantLock lock:用于保证线程安全,实现了独占锁机制。
  • Condition trip:线程阻塞时的等待条件。
  • int parties:需要等待的线程数。
  • Runnable barrierCommand:栅栏打开时首先执行的任务。
  • Generation generation:记录当前栅栏所处的代号。
  • int count:当前还需要等待的线程数。

2. 构造函数

CyclicBarrier 提供两个重载构造函数:

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

3. 核心方法

3.1 await方法

  • await():无参数版本,调用dowait(false, 0L)
  • await(long timeout, TimeUnit unit):带有超时参数,调用dowait(true, unit.toNanos(timeout))

3.2 dowait方法

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) {            boolean ranAction = false;            try {                final Runnable command = barrierCommand;                if (command != null)                    command.run();                ranAction = true;                nextGeneration();                return 0;            } finally {                if (!ranAction)                    breakBarrier();            }        }        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 {                    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();    }}

3.2.1 breakBarrier方法

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

3.2.2 nextGeneration方法

private void nextGeneration() {    trip.signalAll();    count = parties;    generation = new Generation();}

3.2.3 reset方法

public void reset() {    final ReentrantLock lock = this.lock;    lock.lock();    try {        breakBarrier();        nextGeneration();    } finally {        lock.unlock();    }}

4. 问题解析

4.1 dowait中的锁释放问题

dowait方法中,锁是在finally块中释放的。第一个线程获取锁后进入等待状态,其他线程如何获取锁?答案在于Conditionawait方法内部,通过unparkSuccessor唤醒后继线程,允许它们获取锁继续执行。

5. 更新日志

  • 3.19日更新了问题解析的问题1。

转载地址:http://slkkz.baihongyu.com/

你可能感兴趣的文章
python 使用in判断不准确,in不好使
查看>>
Python 使用pandas 进行查询和统计详解
查看>>
Redis 配置文件redis.conf详细解释
查看>>
python网络爬虫(2)——scrapy框架的基础使用
查看>>
python网络爬虫实例教程试读_Python网络爬虫实战教程(全套完整版) - 学途无忧网 - 做技术的王者 - Powered By EduSoho...
查看>>
Python 使用哈希函数用于加密
查看>>
Python 依赖管理的革新——Poetry 深度解析
查看>>
python 保留精度及增加去除数字的千位分隔符(金额化数字)
查看>>
python 倒计时 9,8,7,。。。。。。0
查看>>
Python 入门开发学习笔记之数据的增删改查
查看>>
Python 入门教程(2)搭建环境 2.4、VSCode配置Node.js运行环境
查看>>
Python 八大排序算法合集
查看>>
python 关于epoll的学习
查看>>
Python 内存管理
查看>>
Python 内嵌函数:它们有什么用处?
查看>>
Python 内置 sum 函数 vs. for 循环性能
查看>>
python 内置slice的用法
查看>>
Python 内置时间模块
查看>>
python 内部如何实现命名元组?
查看>>
Python 写Android App性能:入门到高级
查看>>