ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CyclicBarrier.java
Revision: 1.7
Committed: Tue Aug 5 22:50:28 2003 UTC (20 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.6: +3 -15 lines
Log Message:
Fixed some typos and docs

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