0
点赞
收藏
分享

微信扫一扫

CyclicBarrier源码解析


1. 先看一下构造函数

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

parties: 官方翻译​​the number of threads that must invoke {@link #await} before the barrier is tripped​​​ 也就是直到调用parties次await()方法,程序才继续执行,否则线程会阻塞在​​await()​​方法这里。

barrierAction:​​the command to execute when the barrier is tripped, or {@code null} if there is no action​​ 程序继续执行时回调的方法

2. 属性

private static class Generation {
Generation() {} // prevent access constructor creation
boolean broken; // initially 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;

/**
* Updates state on barrier trip and wakes up everyone.
* Called only while holding lock.
*/
private void nextGeneration() {
// signal completion of last generation
trip.signalAll();
// set up next generation
count = parties;
generation = new Generation();
}

根据属性可以看出,内部使用lock锁实现的,generation 实现了cyclic功能,每次把count重新赋值为parties,可以认为对这个类做了初始化

3. await()方法

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

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

dowait()方法为整个CyclicBarrier类的核心实现,线程等待数量不满足parties时等待,满足了,唤醒所有线程同时调用​​nextGeneration​​​生产新的generation,这样就可以实现​​cyclic​​的功能了。

在​​nextGeneration()​​​方法中为什么每次都要生产调用​​generation = new Generation()​​ ?

​Generation​​​类里面有一个状态​​broken​​​,其它在​​await()​​​方法上等待的线程还需要监控这个状态,因为有可能因为某线程等待超时触发​​InterruptedException​​​异常,此时会把​​broken=true​​,并且唤醒所有线程。

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

构造函数中的回调方法由最后一个进来的线程调用run()方法执行,因为只有最后一个进来的线程​​--count​​后才会等于0

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

实时内容请关注微信公众号,公众号与博客同时更新:程序员星星

CyclicBarrier源码解析_源码解析


举报

相关推荐

0 条评论