前言
- 一种同步辅助工具,它允许一组线程全部互相等待以到达一个公共的障碍点。
- CyclicBarriers在涉及固定大小的线程方的程序中很有用,该线程方有时必须互相等待。
- 该屏障称为循环屏障,因为它可以在释放等待线程之后重新使用。
- {@code CyclicBarrier}支持可选的{@link Runnable}命令,该命令在障碍中的最后一个线程到达之后但在释放任何线程之前,每个障碍点运行一次。
- 此屏障操作对于在任何一方继续之前更新共享状态很有用。
- 屏障的每次使用都表示为一个生成实例。
- 每当隔离栅被触发或重置时,生成都会更改。
- 使用屏障可以与线程相关联的世代很多-由于非确定性方式可以将锁分配给等待的线程-但一次只能激活其中之一({@code count}适用于那一代) ),其余的全部损坏或绊倒。
- 如果有中断但没有后续的重置,则不需要活跃的生成。
源码
package java.util.concurrent;
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();
/**
* 仍在等待的party数量。从party倒数到每一代的0。在每个generation或当generation破碎时,都会将其重置。
*/
private int count;
/**
* Updates state on barrier trip and wakes up everyone.
* Called only while holding lock.
*/
private void nextGeneration() {
trip.signalAll();
count = parties;
generation = new Generation();
}
/**
* Sets current barrier generation as broken and wakes up everyone.
* Called only while holding lock.
*/
private void breakBarrier() {
generation.broken = true;
count = parties;
trip.signalAll();
}
/**
* Main barrier code, covering the various policies.
*/
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 {
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();
}
}
/**
* 创建一个新的{@code CyclicBarrier},它将在给定数量的参与者(线程)等待它时将跳闸,并在屏障被跳闸时执行给定的屏障动作,该动作由最后一个进入屏障的线程执行。
*/
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
/**
* 创建一个新的{@code CyclicBarrier},当给定数量的参与者(线程)正在等待它时,它将跳闸,而当屏障被跳闸时,它不执行预定义的操作。
*
*
* @param parties the number of threads that must invoke {@link
* before the barrier is tripped
* @throws IllegalArgumentException if {@code parties} is less than 1
*/
public CyclicBarrier(int parties) {
this(parties, null);
}
/**
* Returns the number of parties required to trip this barrier.
*
* @return the number of parties required to trip this barrier
*/
public int getParties() {
return parties;
}
/**
* 等待所有{@linkplain
* 如果当前线程不是最后到达的线程,则出于线程调度目的将其禁用,并且在发生以下情况之一之前,它处于休眠状态:或其他某个线程{@linkplain Thread#interrupt interrupts}当前线程;或其他一些线程{@linkplain Thread#interrupt interrupts}其他等待线程之一;或者在等待屏障时其他线程超时;或其他线程在此障碍上调用{@link
* 如果当前线程:在进入此方法时设置了其中断状态;或在等待期间{@linkplain Thread#interrupt被中断},然后引发{@link InterruptedException}并清除了当前线程的中断状态。
* 如果在任何线程正在等待时屏障是{@link
* 如果任何线程在等待时{@linkplain Thread#interrupt被中断},则所有其他等待线程将抛出{@link BrokenBarrierException},并且屏障处于断开状态。
* 如果当前线程是最后到达的线程,并且在构造函数中提供了非null屏障操作,则当前线程将在允许其他线程继续运行之前运行该操作。
* 如果在屏障操作期间发生异常,则该异常将在当前线程中传播,并且屏障处于断开状态。
*
*/
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
/**
* 等待直到所有{@linkplain
* 如果当前线程不是最后到达的线程,则出于线程调度目的将其禁用,并且在发生以下情况之一之前,它处于休眠状态:或经过指定的超时时间;或其他某个线程{@linkplain Thread#interrupt interrupts}当前线程;或其他一些线程{@linkplain Thread#interrupt interrupts}其他等待线程之一;或者在等待屏障时其他线程超时;或其他线程在此障碍上调用{@link
* 如果当前线程:在进入此方法时设置了其中断状态;或在等待期间{@linkplain Thread#interrupt被中断},然后引发{@link InterruptedException}并清除了当前线程的中断状态。
* 如果经过了指定的等待时间,则抛出{@link TimeoutException}。
* 如果时间小于或等于零,则该方法将根本不等待。
* 如果在任何线程正在等待时屏障是{@link
* 如果任何线程在等待时{@linkplain Thread#interrupt被中断},则所有其他等待线程将抛出{@link BrokenBarrierException},并且屏障处于断开状态。
* 如果当前线程是最后到达的线程,并且在构造函数中提供了非null屏障操作,则当前线程将在允许其他线程继续运行之前运行该操作。
* 如果在屏障操作期间发生异常,则该异常将在当前线程中传播,并且屏障处于断开状态。
*
*/
public int await(long timeout, TimeUnit unit)
throws InterruptedException,
BrokenBarrierException,
TimeoutException {
return dowait(true, unit.toNanos(timeout));
}
/**
* Queries if this barrier is in a broken state.
*
* @return {@code true} if one or more parties broke out of this
* barrier due to interruption or timeout since
* construction or the last reset, or a barrier action
* failed due to an exception; {@code false} otherwise.
*/
public boolean isBroken() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return generation.broken;
} finally {
lock.unlock();
}
}
/**
* 将屏障重置为其初始状态。
* 如果任何一方当前正在等待障碍,他们将返回{@link BrokenBarrierException}。
* 请注意,由于其他原因发生破损后的复位操作可能会很复杂。
* 线程需要以其他某种方式重新同步,然后选择一种执行重置。
* 相反,最好为以后的使用创建一个新的屏障。
*
*/
public void reset() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
breakBarrier(); // break the current generation
nextGeneration(); // start a new generation
} finally {
lock.unlock();
}
}
/**
* 返回当前在障碍处等待的参与者数量。此方法主要用于调试和断言。
*/
public int getNumberWaiting() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return parties - count;
} finally {
lock.unlock();
}
}
}