CyclicBarrier:

CyclicBarrier 是一个同步辅助类,允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。如果一个程序中有固定的线程数,并且线程之间需要相互等待,这时候 CyclicBarrier 是一个很好的选择。之所以叫它 cyclic,是因为在释放等待线程之后,它可以被重用。还是那句话,开始之前你需要先了解 AQS 的实现机制。

CountDownLatchCyclicBarrier 的区别:

  • CountDownLatch 的作用是允许1N个线程等待其他线程完成执行;而 CyclicBarrier 则是允许N个线程相互等待。
  • CountDownLatch 的计数器无法被重置;CyclicBarrier 的计数器可以被重置后使用,因此它被称为是循环的 barrier

核心属性

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
/**
* Each use of the barrier is represented as a generation instance.
* The generation changes whenever the barrier is tripped, or
* is reset. There can be many generations associated with threads
* using the barrier - due to the non-deterministic way the lock
* may be allocated to waiting threads - but only one of these
* can be active at a time (the one to which {@code count} applies)
* and all the rest are either broken or tripped.
* There need not be an active generation if there has been a break
* but no subsequent reset.
*/
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();

/**
* 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;
  1. lock: 守护 barrier 入口的锁, 关于 ReentrantLock 请查看 并发编程 - ReentrantLock
  2. trip: 等待条件,直到所有线程到达 barrier
  3. parties: 要屏障的线程数
  4. barrierCommand: 当线程都到达 barrier,运行的 barrierCommandCyclicBarrier 的另一个特性是在所有参与线程到达 barrier 触发一个自定义函数,这个函数就是 barrierCommand,在 CyclicBarrier 的构造函数中初始化。
  5. generation: 每个使用中的 barrier 都表示为一个 generation 实例。当 barrier 触发 trip 条件或重置时 generation 随之改变。使用 barrier 时有很多 generation 与线程关联,由于不确定性的方式,锁可能分配给等待的线程。但是在同一时间只有一个是活跃的 generation (通过count变量确定),并且其余的要么被销毁,要么被 trip 条件等待。如果有一个中断,但没有随后的重置,就不需要有活跃的 generationCyclicBarrier 的可重用特性就是通过 Generation 来实现,每一次触发 tripped 都会 new 一个新的 Generation
  6. count: 等待到达 barrier 的参与线程数量,count=0 -> tripped

构造函数

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
/**
* Creates a new {@code CyclicBarrier} that will trip when the
* given number of parties (threads) are waiting upon it, and which
* will execute the given barrier action when the barrier is tripped,
* performed by the last thread entering the barrier.
*
* @param parties the number of threads that must invoke {@link #await}
* before the barrier is tripped
* @param barrierAction the command to execute when the barrier is
* tripped, or {@code null} if there is no action
* @throws IllegalArgumentException if {@code parties} is less than 1
*/
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}

/**
* Creates a new {@code CyclicBarrier} that will trip when the
* given number of parties (threads) are waiting upon it, and
* does not perform a predefined action when the barrier is tripped.
*
* @param parties the number of threads that must invoke {@link #await}
* before the barrier is tripped
* @throws IllegalArgumentException if {@code parties} is less than 1
*/
public CyclicBarrier(int parties) {
this(parties, null);
}
  • parties 指定执行的线程数量,在 barriertrip 之前必要有 parties 个线程调用 await 方法
  • barrierActionbarriertrip 时会执行该方法,可以为空

核心方法

await

awaitCyclicBarrier 的核心方法,执行 await 会调用内部方法 dowait,await 支持超时响应,当超过指定时间还未达到 barrier,就会抛出 TimeoutException.

1
2
3
4
5
6
7
8
9
10
11
12
13
public int await() throws InterruptedException, BrokenBarrierException {
try {
return dowait(false, 0L);
} catch (TimeoutException toe) {
throw new Error(toe); // cannot happen
}
}
public int await(long timeout, TimeUnit unit)
throws InterruptedException,
BrokenBarrierException,
TimeoutException {
return dowait(true, unit.toNanos(timeout));
}

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
/**
* 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 {
// 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();
}
}
  1. lock 获取互斥锁,lock 操作会一直等待直到获取到锁资源
  2. 判断 barrier 是否已经 broken,如果 broken 就抛出 BrokenBarrierException 异常
  3. 判断线程是否已经中断,如果已经中断就抛出 InterruptedException 异常
  4. count1, count 表示当前还未到达 barrier 的线程数量
  5. 如果 count0, 表示所有线程都已到达 barrier,就是执行 barrierCommand,并重置 Generation 返回 0
  6. 否则就会进入循环,直到 tripbroken、中断 或者超时跳出循环

nextGenerateion 方法更新障碍的状态并唤醒所有线程。

1
2
3
4
5
6
7
8
9
10
11
/**
* 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();
}

breakBarrier 方法设置当前 barrierGennerationbroken 并唤醒所有线程

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

reset

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

/**
* Resets the barrier to its initial state. If any parties are
* currently waiting at the barrier, they will return with a
* {@link BrokenBarrierException}. Note that resets <em>after</em>
* a breakage has occurred for other reasons can be complicated to
* carry out; threads need to re-synchronize in some other way,
* and choose one to perform the reset. It may be preferable to
* instead create a new barrier for subsequent use.
*/
public void reset() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
breakBarrier(); // break the current generation
nextGeneration(); // start a new generation
} finally {
lock.unlock();
}
}

该方法就是与 CountDownLatch 区别的核心, CountDownLatch 只能使用一次,而 CyclicBarrier 可以无限 reset 重置 barrier 的状态,循环(Cyclic)使用。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(10, () -> System.out.println("人都到齐了。"));
for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
// 假设每个人达到办公室的时间不一致
Thread.sleep((long) (Math.random() * 10_000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("第【%s】个人到达会议室",Thread.currentThread().getName()));
try {
cyclicBarrier.await(1, TimeUnit.SECONDS);
System.out.println(String.format("【%s】开始开会",Thread.currentThread().getName()));
} catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
e.printStackTrace();
}
}, String.valueOf(i + 1)).start();
}
cyclicBarrier.reset();
}

参考

JUC源码分析-CyclicBarrier