ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CyclicBarrier.java
Revision: 1.10
Committed: Sat Aug 23 19:47:29 2003 UTC (20 years, 9 months ago) by tim
Branch: MAIN
Changes since 1.9: +3 -3 lines
Log Message:
"set [of] threads" typo fixed

File Contents

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