ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CyclicBarrier.java
Revision: 1.11
Committed: Mon Aug 25 22:32:40 2003 UTC (20 years, 9 months ago) by dholmes
Branch: MAIN
Changes since 1.10: +11 -5 lines
Log Message:
Added missing "catch (Error ex)" clause in dowAwait after running
barrier action.
Minor formatting changes.

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain. Use, modify, and
4 * redistribute this code in any way without acknowledgement.
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 or timeout, all others
86 * will also leave abnormally (via {@link BrokenBarrierException}),
87 * until the barrier is {@link #reset}. This is usually the simplest
88 * and best strategy for sharing knowledge about failures among
89 * cooperating threads in the most common usage contexts of barriers.
90 *
91 * @since 1.5
92 * @spec JSR-166
93 * @revised $Date: 2003/08/23 19:47:29 $
94 * @editor $Author: tim $
95 * @see CountDownLatch
96 *
97 * @author Doug Lea
98 */
99 public class CyclicBarrier {
100 /** The lock for guarding barrier entry */
101 private final ReentrantLock lock = new ReentrantLock();
102 /** Condition to wait on until tripped */
103 private final Condition trip = lock.newCondition();
104 /** The number of parties */
105 private final int parties;
106 /* The command to run when tripped */
107 private Runnable barrierCommand;
108
109 /**
110 * The generation number. Incremented mod Integer.MAX_VALUE every
111 * time barrier tripped. Starts at 1 to simplify handling of
112 * breakage indicator
113 */
114 private int generation = 1;
115
116 /**
117 * Breakage indicator: last generation of breakage, propagated
118 * across barrier generations until reset.
119 */
120 private int broken = 0;
121
122 /**
123 * Number of parties still waiting. Counts down from parties to 0
124 * on each cycle.
125 */
126 private int count;
127
128 /**
129 * Update state on barrier trip.
130 */
131 private void nextGeneration() {
132 count = parties;
133 int g = generation;
134 // avoid generation == 0
135 if (++generation < 0) generation = 1;
136 // propagate breakage
137 if (broken == g) broken = generation;
138 }
139
140 /**
141 * Main barrier code, covering the various policies.
142 */
143 private int dowait(boolean timed, long nanos)
144 throws InterruptedException, BrokenBarrierException, TimeoutException {
145 lock.lock();
146 try {
147 int index = --count;
148 int g = generation;
149
150 if (broken == g)
151 throw new BrokenBarrierException();
152
153 if (Thread.interrupted()) {
154 broken = g;
155 trip.signalAll();
156 throw new InterruptedException();
157 }
158
159 if (index == 0) { // tripped
160 nextGeneration();
161 trip.signalAll();
162 try {
163 if (barrierCommand != null)
164 barrierCommand.run();
165 return 0;
166 } catch (RuntimeException ex) {
167 broken = generation; // next generation is broken
168 throw ex;
169 }
170 catch (Error ex) {
171 broken = generation; // next generation is broken
172 throw ex;
173 }
174 }
175
176 while (generation == g) {
177 try {
178 if (!timed)
179 trip.await();
180 else if (nanos > 0)
181 nanos = trip.awaitNanos(nanos);
182 } catch (InterruptedException ex) {
183 // Only claim that broken if interrupted before reset
184 if (generation == g) {
185 broken = g;
186 trip.signalAll();
187 throw ex;
188 } else {
189 Thread.currentThread().interrupt(); // propagate
190 break;
191 }
192 }
193
194 if (timed && nanos <= 0) {
195 broken = g;
196 trip.signalAll();
197 throw new TimeoutException();
198 }
199
200 if (broken == g)
201 throw new BrokenBarrierException();
202
203 }
204 return index;
205
206 } finally {
207 lock.unlock();
208 }
209 }
210
211 /**
212 * Create a new <tt>CyclicBarrier</tt> that will trip when the
213 * given number of parties (threads) are waiting upon it, and which
214 * will execute the given barrier action when the barrier is tripped.
215 *
216 * @param parties the number of threads that must invoke {@link #await}
217 * before the barrier is tripped.
218 * @param barrierAction the command to execute when the barrier is
219 * tripped.
220 *
221 * @throws IllegalArgumentException if <tt>parties</tt> is less than 1.
222 */
223 public CyclicBarrier(int parties, Runnable barrierAction) {
224 if (parties <= 0) throw new IllegalArgumentException();
225 this.parties = parties;
226 this.count = parties;
227 this.barrierCommand = barrierAction;
228 }
229
230 /**
231 * Create a new <tt>CyclicBarrier</tt> that will trip when the
232 * given number of parties (threads) are waiting upon it.
233 *
234 * <p>This is equivalent to <tt>CyclicBarrier(parties, null)</tt>.
235 *
236 * @param parties the number of threads that must invoke {@link #await}
237 * before the barrier is tripped.
238 *
239 * @throws IllegalArgumentException if <tt>parties</tt> is less than 1.
240 */
241 public CyclicBarrier(int parties) {
242 this(parties, null);
243 }
244
245 /**
246 * Return the number of parties required to trip this barrier.
247 * @return the number of parties required to trip this barrier.
248 **/
249 public int getParties() {
250 return parties;
251 }
252
253 /**
254 * Wait until all {@link #getParties parties} have invoked <tt>await</tt>
255 * on this barrier.
256 *
257 * <p>If the current thread is not the last to arrive then it is
258 * disabled for thread scheduling purposes and lies dormant until
259 * one of following things happens:
260 * <ul>
261 * <li>The last thread arrives; or
262 * <li>Some other thread {@link Thread#interrupt interrupts} the current
263 * thread; or
264 * <li>Some other thread {@link Thread#interrupt interrupts} one of the
265 * other waiting threads; or
266 * <li>Some other thread times out while waiting for barrier; or
267 * <li>Some other thread invokes {@link #reset} on this barrier.
268 * </ul>
269 * <p>If the current thread:
270 * <ul>
271 * <li>has its interrupted status set on entry to this method; or
272 * <li>is {@link Thread#interrupt interrupted} while waiting
273 * </ul>
274 * then {@link InterruptedException} is thrown and the current thread's
275 * interrupted status is cleared.
276 *
277 * <p>If the barrier is {@link #reset} while any thread is waiting, or if
278 * the barrier {@link #isBroken is broken} when <tt>await</tt> is invoked
279 * then {@link BrokenBarrierException} is thrown.
280 *
281 * <p>If any thread is {@link Thread#interrupt interrupted} while waiting,
282 * then all other waiting threads will throw
283 * {@link BrokenBarrierException} and the barrier is placed in the broken
284 * state.
285 *
286 * <p>If the current thread is the last thread to arrive, and a
287 * non-null barrier action was supplied in the constructor, then the
288 * current thread runs the action before allowing the other threads to
289 * continue.
290 * If an exception occurs during the barrier action then that exception
291 * will be propagated in the current thread.
292 *
293 * @return the arrival index of the current thread, where index
294 * <tt>{@link #getParties()} - 1</tt> indicates the first to arrive and
295 * zero indicates the last to arrive.
296 *
297 * @throws InterruptedException if the current thread was interrupted
298 * while waiting
299 * @throws BrokenBarrierException if <em>another</em> thread was
300 * interrupted while the current thread was waiting, or the barrier was
301 * reset, or the barrier was broken when <tt>await</tt> was called.
302 */
303 public int await() throws InterruptedException, BrokenBarrierException {
304 try {
305 return dowait(false, 0);
306 } catch (TimeoutException toe) {
307 throw new Error(toe); // cannot happen;
308 }
309 }
310
311 /**
312 * Wait until all {@link #getParties parties} have invoked <tt>await</tt>
313 * on this barrier.
314 *
315 * <p>If the current thread is not the last to arrive then it is
316 * disabled for thread scheduling purposes and lies dormant until
317 * one of the following things happens:
318 * <ul>
319 * <li>The last thread arrives; or
320 * <li>The speceified timeout elapses; or
321 * <li>Some other thread {@link Thread#interrupt interrupts} the current
322 * thread; or
323 * <li>Some other thread {@link Thread#interrupt interrupts} one of the
324 * other waiting threads; or
325 * <li>Some other thread times out while waiting for barrier; or
326 * <li>Some other thread invokes {@link #reset} on this barrier.
327 * </ul>
328 * <p>If the current thread:
329 * <ul>
330 * <li>has its interrupted status set on entry to this method; or
331 * <li>is {@link Thread#interrupt interrupted} while waiting
332 * </ul>
333 * then {@link InterruptedException} is thrown and the current thread's
334 * interrupted status is cleared.
335 *
336 * <p>If the barrier is {@link #reset} while any thread is waiting, or if
337 * the barrier {@link #isBroken is broken} when <tt>await</tt> is invoked
338 * then {@link BrokenBarrierException} is thrown.
339 *
340 * <p>If any thread is {@link Thread#interrupt interrupted} while waiting,
341 * then all other waiting threads will throw
342 * {@link BrokenBarrierException} and the barrier is placed in the broken
343 * state.
344 *
345 * <p>If the current thread is the last thread to arrive, and a
346 * non-null barrier action was supplied in the constructor, then the
347 * current thread runs the action before allowing the other threads to
348 * continue.
349 * If an exception occurs during the barrier action then that exception
350 * will be propagated in the current thread.
351 *
352 * @param timeout the time to wait for the barrier
353 * @param unit the time unit of the timeout parameter
354 * @return the arrival index of the current thread, where index
355 * <tt>{@link #getParties()} - 1</tt> indicates the first to arrive and
356 * zero indicates the last to arrive.
357 *
358 * @throws InterruptedException if the current thread was interrupted
359 * while waiting
360 * @throws TimeoutException if the specified timeout elapses.
361 * @throws BrokenBarrierException if <em>another</em> thread was
362 * interrupted while the current thread was waiting, or the barrier was
363 * reset, or the barrier was broken when <tt>await</tt> was called.
364 */
365 public int await(long timeout, TimeUnit unit)
366 throws InterruptedException,
367 BrokenBarrierException,
368 TimeoutException {
369 return dowait(true, unit.toNanos(timeout));
370 }
371
372 /**
373 * Query if this barrier is in a broken state.
374 * @return <tt>true</tt> if one or more parties broke out of this
375 * barrier due to interruption or timeout since construction or
376 * the last reset; and <tt>false</tt> otherwise.
377 */
378 public boolean isBroken() {
379 lock.lock();
380 try {
381 return broken >= generation;
382 } finally {
383 lock.unlock();
384 }
385 }
386
387 /**
388 * Reset the barrier to its initial state. If any parties are
389 * currently waiting at the barrier, they will return with a
390 * {@link BrokenBarrierException}. Note that resets <em>after</em>
391 * a breakage can be complicated to carry out; threads need to
392 * re-synchronize in some other way, and choose one to perform the
393 * reset. It may be preferable to instead create a new barrier
394 * for subsequent use.
395 */
396 public void reset() {
397 lock.lock();
398 try {
399 int g = generation;
400 nextGeneration();
401 broken = g; // cause brokenness setting to stop at previous gen.
402 trip.signalAll();
403 } finally {
404 lock.unlock();
405 }
406 }
407
408 /**
409 * Return the number of parties currently waiting at the barrier.
410 * This method is primarily useful for debugging and assertions.
411 *
412 * @return the number of parties currently blocked in {@link #await}
413 **/
414 public int getNumberWaiting() {
415 lock.lock();
416 try {
417 return parties - count;
418 } finally {
419 lock.unlock();
420 }
421 }
422
423 }