1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
import java.util.concurrent.locks.Condition; |
10 |
import java.util.concurrent.locks.ReentrantLock; |
11 |
|
12 |
/** |
13 |
* A synchronization aid that allows a set of threads to all wait for |
14 |
* each other to reach a common barrier point. CyclicBarriers are |
15 |
* useful in programs involving a fixed sized party of threads that |
16 |
* must occasionally wait for each other. The barrier is called |
17 |
* <em>cyclic</em> because it can be re-used after the waiting threads |
18 |
* are released. |
19 |
* |
20 |
* <p>A {@code CyclicBarrier} supports an optional {@link Runnable} command |
21 |
* that is run once per barrier point, after the last thread in the party |
22 |
* arrives, but before any threads are released. |
23 |
* This <em>barrier action</em> is useful |
24 |
* for updating shared-state before any of the parties continue. |
25 |
* |
26 |
* <p><b>Sample usage:</b> Here is an example of |
27 |
* using a barrier in a parallel decomposition design: |
28 |
* |
29 |
* <pre> {@code |
30 |
* class Solver { |
31 |
* final int N; |
32 |
* final float[][] data; |
33 |
* final CyclicBarrier barrier; |
34 |
* |
35 |
* class Worker implements Runnable { |
36 |
* int myRow; |
37 |
* Worker(int row) { myRow = row; } |
38 |
* public void run() { |
39 |
* while (!done()) { |
40 |
* processRow(myRow); |
41 |
* |
42 |
* try { |
43 |
* barrier.await(); |
44 |
* } catch (InterruptedException ex) { |
45 |
* return; |
46 |
* } catch (BrokenBarrierException ex) { |
47 |
* return; |
48 |
* } |
49 |
* } |
50 |
* } |
51 |
* } |
52 |
* |
53 |
* public Solver(float[][] matrix) { |
54 |
* data = matrix; |
55 |
* N = matrix.length; |
56 |
* barrier = new CyclicBarrier(N, |
57 |
* new Runnable() { |
58 |
* public void run() { |
59 |
* mergeRows(...); |
60 |
* } |
61 |
* }); |
62 |
* for (int i = 0; i < N; ++i) |
63 |
* new Thread(new Worker(i)).start(); |
64 |
* |
65 |
* waitUntilDone(); |
66 |
* } |
67 |
* }}</pre> |
68 |
* |
69 |
* Here, each worker thread processes a row of the matrix then waits at the |
70 |
* barrier until all rows have been processed. When all rows are processed |
71 |
* the supplied {@link Runnable} barrier action is executed and merges the |
72 |
* rows. If the merger |
73 |
* determines that a solution has been found then {@code done()} will return |
74 |
* {@code true} and each worker will terminate. |
75 |
* |
76 |
* <p>If the barrier action does not rely on the parties being suspended when |
77 |
* it is executed, then any of the threads in the party could execute that |
78 |
* action when it is released. To facilitate this, each invocation of |
79 |
* {@link #await} returns the arrival index of that thread at the barrier. |
80 |
* You can then choose which thread should execute the barrier action, for |
81 |
* example: |
82 |
* <pre> {@code |
83 |
* if (barrier.await() == 0) { |
84 |
* // log the completion of this iteration |
85 |
* }}</pre> |
86 |
* |
87 |
* <p>The {@code CyclicBarrier} uses an all-or-none breakage model |
88 |
* for failed synchronization attempts: If a thread leaves a barrier |
89 |
* point prematurely because of interruption, failure, or timeout, all |
90 |
* other threads waiting at that barrier point will also leave |
91 |
* abnormally via {@link BrokenBarrierException} (or |
92 |
* {@link InterruptedException} if they too were interrupted at about |
93 |
* the same time). |
94 |
* |
95 |
* <p>Memory consistency effects: Actions in a thread prior to calling |
96 |
* {@code await()} |
97 |
* <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> |
98 |
* actions that are part of the barrier action, which in turn |
99 |
* <i>happen-before</i> actions following a successful return from the |
100 |
* corresponding {@code await()} in other threads. |
101 |
* |
102 |
* @since 1.5 |
103 |
* @see CountDownLatch |
104 |
* |
105 |
* @author Doug Lea |
106 |
*/ |
107 |
public class CyclicBarrier { |
108 |
/** |
109 |
* Each use of the barrier is represented as a generation instance. |
110 |
* The generation changes whenever the barrier is tripped, or |
111 |
* is reset. There can be many generations associated with threads |
112 |
* using the barrier - due to the non-deterministic way the lock |
113 |
* may be allocated to waiting threads - but only one of these |
114 |
* can be active at a time (the one to which {@code count} applies) |
115 |
* and all the rest are either broken or tripped. |
116 |
* There need not be an active generation if there has been a break |
117 |
* but no subsequent reset. |
118 |
*/ |
119 |
private static class Generation { |
120 |
boolean broken = false; |
121 |
} |
122 |
|
123 |
/** The lock for guarding barrier entry */ |
124 |
private final ReentrantLock lock = new ReentrantLock(); |
125 |
/** Condition to wait on until tripped */ |
126 |
private final Condition trip = lock.newCondition(); |
127 |
/** The number of parties */ |
128 |
private final int parties; |
129 |
/** The command to run when tripped */ |
130 |
private final Runnable barrierCommand; |
131 |
/** The current generation */ |
132 |
private Generation generation = new Generation(); |
133 |
|
134 |
/** |
135 |
* Number of parties still waiting. Counts down from parties to 0 |
136 |
* on each generation. It is reset to parties on each new |
137 |
* generation or when broken. |
138 |
*/ |
139 |
private int count; |
140 |
|
141 |
/** |
142 |
* Updates state on barrier trip and wakes up everyone. |
143 |
* Called only while holding lock. |
144 |
*/ |
145 |
private void nextGeneration() { |
146 |
// signal completion of last generation |
147 |
trip.signalAll(); |
148 |
// set up next generation |
149 |
count = parties; |
150 |
generation = new Generation(); |
151 |
} |
152 |
|
153 |
/** |
154 |
* Sets current barrier generation as broken and wakes up everyone. |
155 |
* Called only while holding lock. |
156 |
*/ |
157 |
private void breakBarrier() { |
158 |
generation.broken = true; |
159 |
count = parties; |
160 |
trip.signalAll(); |
161 |
} |
162 |
|
163 |
/** |
164 |
* Main barrier code, covering the various policies. |
165 |
*/ |
166 |
private int dowait(boolean timed, long nanos) |
167 |
throws InterruptedException, BrokenBarrierException, |
168 |
TimeoutException { |
169 |
final ReentrantLock lock = this.lock; |
170 |
lock.lock(); |
171 |
try { |
172 |
final Generation g = generation; |
173 |
|
174 |
if (g.broken) |
175 |
throw new BrokenBarrierException(); |
176 |
|
177 |
if (Thread.interrupted()) { |
178 |
breakBarrier(); |
179 |
throw new InterruptedException(); |
180 |
} |
181 |
|
182 |
int index = --count; |
183 |
if (index == 0) { // tripped |
184 |
boolean ranAction = false; |
185 |
try { |
186 |
final Runnable command = barrierCommand; |
187 |
if (command != null) |
188 |
command.run(); |
189 |
ranAction = true; |
190 |
nextGeneration(); |
191 |
return 0; |
192 |
} finally { |
193 |
if (!ranAction) |
194 |
breakBarrier(); |
195 |
} |
196 |
} |
197 |
|
198 |
// loop until tripped, broken, interrupted, or timed out |
199 |
for (;;) { |
200 |
try { |
201 |
if (!timed) |
202 |
trip.await(); |
203 |
else if (nanos > 0L) |
204 |
nanos = trip.awaitNanos(nanos); |
205 |
} catch (InterruptedException ie) { |
206 |
if (g == generation && ! g.broken) { |
207 |
breakBarrier(); |
208 |
throw ie; |
209 |
} else { |
210 |
// We're about to finish waiting even if we had not |
211 |
// been interrupted, so this interrupt is deemed to |
212 |
// "belong" to subsequent execution. |
213 |
Thread.currentThread().interrupt(); |
214 |
} |
215 |
} |
216 |
|
217 |
if (g.broken) |
218 |
throw new BrokenBarrierException(); |
219 |
|
220 |
if (g != generation) |
221 |
return index; |
222 |
|
223 |
if (timed && nanos <= 0L) { |
224 |
breakBarrier(); |
225 |
throw new TimeoutException(); |
226 |
} |
227 |
} |
228 |
} finally { |
229 |
lock.unlock(); |
230 |
} |
231 |
} |
232 |
|
233 |
/** |
234 |
* Creates a new {@code CyclicBarrier} that will trip when the |
235 |
* given number of parties (threads) are waiting upon it, and which |
236 |
* will execute the given barrier action when the barrier is tripped, |
237 |
* performed by the last thread entering the barrier. |
238 |
* |
239 |
* @param parties the number of threads that must invoke {@link #await} |
240 |
* before the barrier is tripped |
241 |
* @param barrierAction the command to execute when the barrier is |
242 |
* tripped, or {@code null} if there is no action |
243 |
* @throws IllegalArgumentException if {@code parties} is less than 1 |
244 |
*/ |
245 |
public CyclicBarrier(int parties, Runnable barrierAction) { |
246 |
if (parties <= 0) throw new IllegalArgumentException(); |
247 |
this.parties = parties; |
248 |
this.count = parties; |
249 |
this.barrierCommand = barrierAction; |
250 |
} |
251 |
|
252 |
/** |
253 |
* Creates a new {@code CyclicBarrier} that will trip when the |
254 |
* given number of parties (threads) are waiting upon it, and |
255 |
* does not perform a predefined action when the barrier is tripped. |
256 |
* |
257 |
* @param parties the number of threads that must invoke {@link #await} |
258 |
* before the barrier is tripped |
259 |
* @throws IllegalArgumentException if {@code parties} is less than 1 |
260 |
*/ |
261 |
public CyclicBarrier(int parties) { |
262 |
this(parties, null); |
263 |
} |
264 |
|
265 |
/** |
266 |
* Returns the number of parties required to trip this barrier. |
267 |
* |
268 |
* @return the number of parties required to trip this barrier |
269 |
*/ |
270 |
public int getParties() { |
271 |
return parties; |
272 |
} |
273 |
|
274 |
/** |
275 |
* Waits until all {@linkplain #getParties parties} have invoked |
276 |
* {@code await} on this barrier. |
277 |
* |
278 |
* <p>If the current thread is not the last to arrive then it is |
279 |
* disabled for thread scheduling purposes and lies dormant until |
280 |
* one of the following things happens: |
281 |
* <ul> |
282 |
* <li>The last thread arrives; or |
283 |
* <li>Some other thread {@linkplain Thread#interrupt interrupts} |
284 |
* the current thread; or |
285 |
* <li>Some other thread {@linkplain Thread#interrupt interrupts} |
286 |
* one of the other waiting threads; or |
287 |
* <li>Some other thread times out while waiting for barrier; or |
288 |
* <li>Some other thread invokes {@link #reset} on this barrier. |
289 |
* </ul> |
290 |
* |
291 |
* <p>If the current thread: |
292 |
* <ul> |
293 |
* <li>has its interrupted status set on entry to this method; or |
294 |
* <li>is {@linkplain Thread#interrupt interrupted} while waiting |
295 |
* </ul> |
296 |
* then {@link InterruptedException} is thrown and the current thread's |
297 |
* interrupted status is cleared. |
298 |
* |
299 |
* <p>If the barrier is {@link #reset} while any thread is waiting, |
300 |
* or if the barrier {@linkplain #isBroken is broken} when |
301 |
* {@code await} is invoked, or while any thread is waiting, then |
302 |
* {@link BrokenBarrierException} is thrown. |
303 |
* |
304 |
* <p>If any thread is {@linkplain Thread#interrupt interrupted} while waiting, |
305 |
* then all other waiting threads will throw |
306 |
* {@link BrokenBarrierException} and the barrier is placed in the broken |
307 |
* state. |
308 |
* |
309 |
* <p>If the current thread is the last thread to arrive, and a |
310 |
* non-null barrier action was supplied in the constructor, then the |
311 |
* current thread runs the action before allowing the other threads to |
312 |
* continue. |
313 |
* If an exception occurs during the barrier action then that exception |
314 |
* will be propagated in the current thread and the barrier is placed in |
315 |
* the broken state. |
316 |
* |
317 |
* @return the arrival index of the current thread, where index |
318 |
* {@code getParties() - 1} indicates the first |
319 |
* to arrive and zero indicates the last to arrive |
320 |
* @throws InterruptedException if the current thread was interrupted |
321 |
* while waiting |
322 |
* @throws BrokenBarrierException if <em>another</em> thread was |
323 |
* interrupted or timed out while the current thread was |
324 |
* waiting, or the barrier was reset, or the barrier was |
325 |
* broken when {@code await} was called, or the barrier |
326 |
* action (if present) failed due to an exception |
327 |
*/ |
328 |
public int await() throws InterruptedException, BrokenBarrierException { |
329 |
try { |
330 |
return dowait(false, 0L); |
331 |
} catch (TimeoutException toe) { |
332 |
throw new Error(toe); // cannot happen |
333 |
} |
334 |
} |
335 |
|
336 |
/** |
337 |
* Waits until all {@linkplain #getParties parties} have invoked |
338 |
* {@code await} on this barrier, or the specified waiting time elapses. |
339 |
* |
340 |
* <p>If the current thread is not the last to arrive then it is |
341 |
* disabled for thread scheduling purposes and lies dormant until |
342 |
* one of the following things happens: |
343 |
* <ul> |
344 |
* <li>The last thread arrives; or |
345 |
* <li>The specified timeout elapses; or |
346 |
* <li>Some other thread {@linkplain Thread#interrupt interrupts} |
347 |
* the current thread; or |
348 |
* <li>Some other thread {@linkplain Thread#interrupt interrupts} |
349 |
* one of the other waiting threads; or |
350 |
* <li>Some other thread times out while waiting for barrier; or |
351 |
* <li>Some other thread invokes {@link #reset} on this barrier. |
352 |
* </ul> |
353 |
* |
354 |
* <p>If the current thread: |
355 |
* <ul> |
356 |
* <li>has its interrupted status set on entry to this method; or |
357 |
* <li>is {@linkplain Thread#interrupt interrupted} while waiting |
358 |
* </ul> |
359 |
* then {@link InterruptedException} is thrown and the current thread's |
360 |
* interrupted status is cleared. |
361 |
* |
362 |
* <p>If the specified waiting time elapses then {@link TimeoutException} |
363 |
* is thrown. If the time is less than or equal to zero, the |
364 |
* method will not wait at all. |
365 |
* |
366 |
* <p>If the barrier is {@link #reset} while any thread is waiting, |
367 |
* or if the barrier {@linkplain #isBroken is broken} when |
368 |
* {@code await} is invoked, or while any thread is waiting, then |
369 |
* {@link BrokenBarrierException} is thrown. |
370 |
* |
371 |
* <p>If any thread is {@linkplain Thread#interrupt interrupted} while |
372 |
* waiting, then all other waiting threads will throw {@link |
373 |
* BrokenBarrierException} and the barrier is placed in the broken |
374 |
* state. |
375 |
* |
376 |
* <p>If the current thread is the last thread to arrive, and a |
377 |
* non-null barrier action was supplied in the constructor, then the |
378 |
* current thread runs the action before allowing the other threads to |
379 |
* continue. |
380 |
* If an exception occurs during the barrier action then that exception |
381 |
* will be propagated in the current thread and the barrier is placed in |
382 |
* the broken state. |
383 |
* |
384 |
* @param timeout the time to wait for the barrier |
385 |
* @param unit the time unit of the timeout parameter |
386 |
* @return the arrival index of the current thread, where index |
387 |
* {@code getParties() - 1} indicates the first |
388 |
* to arrive and zero indicates the last to arrive |
389 |
* @throws InterruptedException if the current thread was interrupted |
390 |
* while waiting |
391 |
* @throws TimeoutException if the specified timeout elapses |
392 |
* @throws BrokenBarrierException if <em>another</em> thread was |
393 |
* interrupted or timed out while the current thread was |
394 |
* waiting, or the barrier was reset, or the barrier was broken |
395 |
* when {@code await} was called, or the barrier action (if |
396 |
* present) failed due to an exception |
397 |
*/ |
398 |
public int await(long timeout, TimeUnit unit) |
399 |
throws InterruptedException, |
400 |
BrokenBarrierException, |
401 |
TimeoutException { |
402 |
return dowait(true, unit.toNanos(timeout)); |
403 |
} |
404 |
|
405 |
/** |
406 |
* Queries if this barrier is in a broken state. |
407 |
* |
408 |
* @return {@code true} if one or more parties broke out of this |
409 |
* barrier due to interruption or timeout since |
410 |
* construction or the last reset, or a barrier action |
411 |
* failed due to an exception; {@code false} otherwise. |
412 |
*/ |
413 |
public boolean isBroken() { |
414 |
final ReentrantLock lock = this.lock; |
415 |
lock.lock(); |
416 |
try { |
417 |
return generation.broken; |
418 |
} finally { |
419 |
lock.unlock(); |
420 |
} |
421 |
} |
422 |
|
423 |
/** |
424 |
* Resets the barrier to its initial state. If any parties are |
425 |
* currently waiting at the barrier, they will return with a |
426 |
* {@link BrokenBarrierException}. Note that resets <em>after</em> |
427 |
* a breakage has occurred for other reasons can be complicated to |
428 |
* carry out; threads need to re-synchronize in some other way, |
429 |
* and choose one to perform the reset. It may be preferable to |
430 |
* instead create a new barrier for subsequent use. |
431 |
*/ |
432 |
public void reset() { |
433 |
final ReentrantLock lock = this.lock; |
434 |
lock.lock(); |
435 |
try { |
436 |
breakBarrier(); // break the current generation |
437 |
nextGeneration(); // start a new generation |
438 |
} finally { |
439 |
lock.unlock(); |
440 |
} |
441 |
} |
442 |
|
443 |
/** |
444 |
* Returns the number of parties currently waiting at the barrier. |
445 |
* This method is primarily useful for debugging and assertions. |
446 |
* |
447 |
* @return the number of parties currently blocked in {@link #await} |
448 |
*/ |
449 |
public int getNumberWaiting() { |
450 |
final ReentrantLock lock = this.lock; |
451 |
lock.lock(); |
452 |
try { |
453 |
return parties - count; |
454 |
} finally { |
455 |
lock.unlock(); |
456 |
} |
457 |
} |
458 |
} |