ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CyclicBarrier.java
Revision: 1.29
Committed: Wed Apr 20 04:35:14 2005 UTC (19 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.28: +7 -8 lines
Log Message:
doc cleanup

File Contents

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