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