CyclicBarrier從字面意思上來看,循環柵欄,這篇文章就來分析下是到底是如何實現循環和柵欄的。
屬性
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();
private int count;
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);
}
CyclicBarrier有兩個構造器,一個接收資源總數,一個接收資源總數和回調線程。回調線程在哪使用,後面再看。
因爲CyclicBarrier是可以重複使用的,那麼就需要有一個變量標識所有的線程是屬於同一個過程的。CyclicBarrier定義了Generation,代際,其中只有一個變量broken,表示當前代際是否被破壞,默認爲false。
await
CyclicBarrier最重要的方法就是await。
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
final ReentrantLock lock = this.lock;
lock.lock();//1、獲取鎖
try {
final Generation g = generation;
//2、是否已更新換代
if (g.broken)
throw new BrokenBarrierException();
//3、是否被中斷
if (Thread.interrupted()) {
//4、跳出柵欄
breakBarrier();
throw new InterruptedException();
}
//5、當前線程到達柵欄,計數減1
int index = --count;
//6、所有線程都到達了柵欄
if (index == 0) { // tripped
boolean ranAction = false;
try {
//7、獲取回調線程
final Runnable command = barrierCommand;
if (command != null)
//8、如果生成時傳入了回調線程,啓動回調線程
command.run();
ranAction = true;
//9、重置,開始下一代
nextGeneration();
return 0;
} finally {
//10、如果ranAction爲false,說明回調線程執行出錯了
if (!ranAction)
//11、跳出柵欄
breakBarrier();
}
}
// loop until tripped, broken, interrupted, or timed out
for (;;) {
try {
if (!timed)
//12、如果不需要超時等待,則立即調用Condition的await
trip.await();
else if (nanos > 0L)
//13、如果需要超時等待
nanos = trip.awaitNanos(nanos);
} catch (InterruptedException ie) {//14、如果等待時被中斷了
//15、如果等待前和現在處於同一代,並且沒有被跳出過
if (g == generation && ! g.broken) {
//16、跳出柵欄
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.
//17、不屬於本代的線程,補中斷
Thread.currentThread().interrupt();
}
}
//18、被其他線程喚醒,此時本代已經被破壞
if (g.broken)
throw new BrokenBarrierException();
//19、不屬於本代,又不是因爲別的線程中斷
if (g != generation)
return index;
//20、如果等待超時,跳出柵欄
if (timed && nanos <= 0L) {
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}
private void breakBarrier() {
//1、更新換代
generation.broken = true;
//2、重置計數
count = parties;
//3、喚醒所有在等待通過柵欄的線程
trip.signalAll();
}
private void nextGeneration() {
// signal completion of last generation
//1、喚醒所有在等待通過柵欄的線程
trip.signalAll();
// set up next generation
//2、重置計數
count = parties;
//3、重新生成代際,此時broken爲false
generation = new Generation();
}
當線程調用了await時,認爲該線程已經到達了柵欄,計數減1,並進入阻塞等待。當最後一個線程到達柵欄時,如果生成時傳入了回調線程,此時執行,然後喚醒所有等待的線程,並更新換代。這是正常的流程。
線程在等待時會被四種情況喚醒:
- 正常流程,最後一個線程達到柵欄後發起的喚醒
- 本線程在等待時被中斷了
- 別的線程發生了中斷,觸發代際破壞,喚醒了等待中的線程
- 本線程等待超時了
如果代際被破壞了,會拋出BrokenBarrierException。
reset
public void reset() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
breakBarrier(); // break the current generation
nextGeneration(); // start a new generation
} finally {
lock.unlock();
}
}
線程也可以調用reset來重置代際,但是這也會導致已經在等待的線程拋出BrokenBarrierException。
對比CountDownLatch
CountDownLatch只能使用一次,而CyclicBarrier支持循環更新代際,多次調用和重置,同時它還提供了所有線程到達柵欄時執行回調的功能。CountDownLatch底層是共享獲取,CyclicBarrier是獨佔獲取(通過調用ReentrantLock)。