ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CyclicBarrier.java
Revision: 1.6
Committed: Tue Jul 8 00:46:33 2003 UTC (20 years, 11 months ago) by dl
Branch: MAIN
CVS Tags: JSR166_PRELIMINARY_TEST_RELEASE_2
Changes since 1.5: +3 -2 lines
Log Message:
Locks in subpackage; fairness params added

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