ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CyclicBarrier.java
Revision: 1.3
Committed: Sat Jun 7 18:20:20 2003 UTC (21 years ago) by dl
Branch: MAIN
CVS Tags: JSR166_PRELIMINARY_TEST_RELEASE_1
Changes since 1.2: +8 -7 lines
Log Message:
Misc documentation updates

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
9 /**
10 * A synchronization aid that allows a set threads to all wait for
11 * each other to reach a common barrier point. CyckicBarriers are
12 * useful in programs involving a fixed sized party of threads that
13 * must occasionally wait for each other. The barrier is
14 * <em>cyclic</em> because it can be re-used after the waiting threads
15 * are released.
16 *
17 * <p>A <tt>CyclicBarrier</tt> supports an optional {@link Runnable} command
18 * that is run once per barrier point, after the last thread in the party
19 * arrives, but before any threads are released.
20 * This <em>barrier action</em> is useful
21 * for updating shared-state before any of the parties continue.
22 *
23 * <p><b>Sample usage:</b> Here is a code sketch of
24 * using a barrier in a parallel decomposition design:
25 * <pre>
26 * class Solver {
27 * final int N;
28 * final float[][] data;
29 * final CyclicBarrier barrier;
30 *
31 * class Worker implements Runnable {
32 * int myRow;
33 * Worker(int row) { myRow = row; }
34 * public void run() {
35 * while (!done()) {
36 * processRow(myRow);
37 *
38 * try {
39 * barrier.await();
40 * }
41 * catch (InterruptedException ex) { return; }
42 * catch (BrokenBarrierException ex) { return; }
43 * }
44 * }
45 * }
46 *
47 * public Solver(float[][] matrix) {
48 * data = matrix;
49 * N = matrix.length;
50 * barrier = new CyclicBarrier(N,
51 * new Runnable() {
52 * public void run() {
53 * mergeRows(...);
54 * }
55 * });
56 * for (int i = 0; i < N; ++i)
57 * new Thread(new Worker(i)).start();
58 *
59 * waitUntilDone();
60 * }
61 * }
62 * </pre>
63 * Here, each worker thread processes a row of the matrix then waits at the
64 * barrier until all rows have been processed. When all rows are processed
65 * the supplied {@link Runnable} barrier action is executed and merges the
66 * rows. If the merger
67 * determines that a solution has been found then <tt>done()</tt> will return
68 * <tt>true</tt> and each worker will terminate.
69 *
70 * <p>If the barrier action does not rely on the parties being suspended when
71 * it is executed, then any of the threads in the party could execute that
72 * action when it is released. To facilitate this, each invocation of
73 * {@link #await} returns the arrival index of that thread at the barrier.
74 * You can then choose which thread should execute the barrier action, for
75 * example:
76 * <pre> if (barrier.await() == 0) {
77 * // log the completion of this iteration
78 * }</pre>
79 *
80 * <p>The <tt>CyclicBarrier</tt> uses an all-or-none breakage model
81 * for failed synchronization attempts: If a thread leaves a barrier
82 * point prematurely because of interruption or timeout, all others
83 * will also leave abnormally (via {@link BrokenBarrierException}),
84 * until the barrier is {@link #reset}. This is usually the simplest
85 * and best strategy for sharing knowledge about failures among
86 * cooperating threads in the most common usage contexts of barriers.
87 *
88 * <h3>Implementation Considerations</h3>
89 * <p>This implementation has the property that interruptions among newly
90 * arriving threads can cause as-yet-unresumed threads from a previous
91 * barrier cycle to return out as broken. This transmits breakage as
92 * early as possible, but with the possible byproduct that only some
93 * threads returning out of a barrier will realize that it is newly
94 * broken. (Others will not realize this until a future cycle.)
95 *
96 *
97 *
98 * @since 1.5
99 * @spec JSR-166
100 * @revised $Date: 2003/05/27 18:14:39 $
101 * @editor $Author: dl $
102 *
103 * @fixme Is the above property actually true in this implementation?
104 * @fixme Should we have a timeout version of await()?
105 */
106 public class CyclicBarrier {
107 private final ReentrantLock lock = new ReentrantLock();
108 private final Condition trip = lock.newCondition();
109 private final int parties;
110 private Runnable barrierCommand;
111
112 /**
113 * The generation number. Incremented mod Integer.MAX_VALUE every
114 * time barrier tripped. Starts at 1 to simplify handling of
115 * breakage indicator
116 */
117 private int generation = 1;
118
119 /**
120 * Breakage indicator: last generation of breakage, propagated
121 * across barrier generations until reset.
122 */
123 private int broken = 0;
124
125 /**
126 * Number of parties still waiting. Counts down from parties to 0
127 * on each cycle.
128 */
129 private int count;
130
131 /**
132 * Update state on barrier trip.
133 */
134 private void nextGeneration() {
135 count = parties;
136 int g = generation;
137 // avoid generation == 0
138 if (++generation < 0) generation = 1;
139 // propagate breakage
140 if (broken == g) broken = generation;
141 }
142
143 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 }
166 catch (RuntimeException ex) {
167 broken = generation; // next generation is broken
168 throw ex;
169 }
170 }
171
172 while (generation == g) {
173 try {
174 if (!timed)
175 trip.await();
176 else if (nanos > 0)
177 nanos = trip.awaitNanos(nanos);
178 }
179 catch (InterruptedException ex) {
180 // Only claim that broken if interrupted before reset
181 if (generation == g) {
182 broken = g;
183 trip.signalAll();
184 throw ex;
185 }
186 else {
187 Thread.currentThread().interrupt(); // propagate
188 break;
189 }
190 }
191
192 if (timed && nanos <= 0) {
193 broken = g;
194 trip.signalAll();
195 throw new TimeoutException();
196 }
197
198 if (broken == generation)
199 throw new BrokenBarrierException();
200
201 }
202 return index;
203
204 }
205 finally {
206 lock.unlock();
207 }
208 }
209
210 /**
211 * Create a new <tt>CyclicBarrier</tt> that will trip when the
212 * given number of parties (threads) are waiting upon it, and which
213 * will execute the given barrier action when the barrier is tripped.
214 *
215 * @param parties the number of threads that must invoke {@link #await}
216 * before the barrier is tripped.
217 * @param barrierAction the command to execute when the barrier is
218 * tripped.
219 *
220 * @throws IllegalArgumentException if <tt>parties</tt> is less than 1.
221 */
222 public CyclicBarrier(int parties, Runnable barrierAction) {
223 if (parties <= 0) throw new IllegalArgumentException();
224 this.parties = parties;
225 this.count = parties;
226 this.barrierCommand = barrierAction;
227 }
228
229 /**
230 * Create a new <tt>CyclicBarrier</tt> that will trip when the
231 * given number of parties (threads) are waiting upon it.
232 *
233 * <p>This is equivalent to <tt>CyclicBarrier(parties, null)</tt>.
234 *
235 * @param parties the number of threads that must invoke {@link #await}
236 * before the barrier is tripped.
237 *
238 * @throws IllegalArgumentException if <tt>parties</tt> is less than 1.
239 */
240 public CyclicBarrier(int parties) {
241 this(parties, null);
242 }
243
244 /**
245 * Return the number of parties required to trip this barrier.
246 * @return the number of parties required to trip this barrier.
247 **/
248 public int getParties() {
249 return parties;
250 }
251
252 /**
253 * Wait until all {@link #getParties parties} have invoked <tt>await</tt>
254 * on this barrier.
255 *
256 * <p>If the current thread is not the last to arrive then it is
257 * disabled for thread scheduling purposes and lies dormant until
258 * one of following things happens:
259 * <ul>
260 * <li>The last thread arrives; or
261 * <li>Some other thread {@link Thread#interrupt interrupts} the current
262 * thread; or
263 * <li>Some other thread {@link Thread#interrupt interrupts} one of the
264 * other waiting threads; or
265 * <li>Some other thread times out while waiting for barrier; or
266 * <li>Some other thread invokes {@link #reset} on this barrier.
267 * </ul>
268 * <p>If the current thread:
269 * <ul>
270 * <li>has its interrupted status set on entry to this method; or
271 * <li>is {@link Thread#interrupt interrupted} while waiting
272 * </ul>
273 * then {@link InterruptedException} is thrown and the current thread's
274 * interrupted status is cleared.
275 *
276 * <p>If the barrier is {@link #reset} while any thread is waiting, or if
277 * the barrier {@link #isBroken is broken} when <tt>await</tt> is invoked
278 * then {@link BrokenBarrierException} is thrown.
279 *
280 * <p>If any thread is {@link Thread#interrupt interrupted} while waiting,
281 * then all other waiting threads will throw
282 * {@link BrokenBarrierException} and the barrier is placed in the broken
283 * state.
284 *
285 * <p>If the current thread is the last thread to arrive, and a
286 * non-null barrier action was supplied in the constructor, then the
287 * current thread runs the action before allowing the other threads to
288 * continue.
289 * If an exception occurs during the barrier action then that exception
290 * will be propagated in the current thread.
291 *
292 * @return the arrival index of the current thread, where index
293 * <tt>{@link #getParties()} - 1</tt> indicates the first to arrive and
294 * zero indicates the last to arrive.
295 *
296 * @throws InterruptedException if the current thread was interrupted
297 * while waiting
298 * @throws BrokenBarrierException if <em>another</em> thread was
299 * interrupted while the current thread was waiting, or the barrier was
300 * reset, or the barrier was broken when <tt>await</tt> was called.
301 */
302 public int await() throws InterruptedException, BrokenBarrierException {
303 try {
304 return dowait(false, 0);
305 }
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 * @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