并发笔记之CyclicBarrier分析

CyclicBarrier是一个同步辅助类,允许一组线程互相等待直到到达一个公共屏障点(common barrier),当涉及到一组固定大小必须相互等待的线程是非常有用的。
他之所以称为cyclic是因为当线程释放,CyclicBarrier可以被重复使用。

主要属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class CyclicBarrier {
/** 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();

/**
* 等待的线程数每一代从parties递减到0
* 当Barrier breaken或者新的一代开始 被重置为parties
*/
private int count;

构造器

1
2
3
4
5
6
7
8
9
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;
}

其构造其有两个参数:

  • parties:表示参与的线程数
  • barriesAction:当达到给定数量的线程处于等待状态 启动barrier时执行给定的屏障操作,此操作由最后进入barrier的线程执行。

等待 await

1
2
3
4
5
6
7
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}

await()最终调用的是超时版本的dowait

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
private int dowait(boolean timed, long nanos)
throws InterruptedException, BrokenBarrierException,
TimeoutException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
final Generation g = generation;
//当前generation已损坏 则抛出BrokenBarrierException异常
if (g.broken)
throw new BrokenBarrierException();
//线程中断则终止barrier
if (Thread.interrupted()) {
breakBarrier();
throw new InterruptedException();
}
//进来一个线程 count自减一
int index = --count;
if (index == 0) { // index==0 表示线程都到位 则执行Runnable任务
boolean ranAction = false;
try {
final Runnable command = barrierCommand;
if (command != null)
command.run();//出发屏障任务
ranAction = true;
nextGeneration();//唤醒所有等待任务 并更新generation
return 0;
} finally {
if (!ranAction)
breakBarrier();
}
}

// loop until tripped, broken, interrupted, or timed out
for (;;) {
try {
if (!timed)//非超时等待 调用Condition.await()一直等待
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)//generation已更新 返回index
return index;

if (timed && nanos <= 0L) {//等待超时 终止barrier 并抛出异常
breakBarrier();
throw new TimeoutException();
}
}
} finally {
lock.unlock();
}
}

换代

当线程都到位,并且最后一个进入的线程成功执行了屏障任务,则调用nextGeneration()方法进行换代 并唤醒所有线程

1
2
3
4
5
6
7
private void nextGeneration() {
// signal completion of last generation
trip.signalAll();
// set up next generation
count = parties;
generation = new Generation();
}

终止Barrier

当线程被中断或线程等待超时 则调用breakBarrier()方法终止Barrier

1
2
3
4
5
private void breakBarrier() {
generation.broken = true;
count = parties;
trip.signalAll();
}

坚持原创技术分享,您的支持将鼓励我继续创作!