ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CyclicBarrier.java
Revision: 1.62
Committed: Fri Nov 27 17:41:59 2020 UTC (3 years, 6 months ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.61: +3 -1 lines
Log Message:
Incorporate snippets code improvements from Pavel Rappo

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