jaroslav@1890: /* jaroslav@1890: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1890: * jaroslav@1890: * This code is free software; you can redistribute it and/or modify it jaroslav@1890: * under the terms of the GNU General Public License version 2 only, as jaroslav@1890: * published by the Free Software Foundation. Oracle designates this jaroslav@1890: * particular file as subject to the "Classpath" exception as provided jaroslav@1890: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1890: * jaroslav@1890: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1890: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1890: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1890: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1890: * accompanied this code). jaroslav@1890: * jaroslav@1890: * You should have received a copy of the GNU General Public License version jaroslav@1890: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1890: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1890: * jaroslav@1890: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1890: * or visit www.oracle.com if you need additional information or have any jaroslav@1890: * questions. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * This file is available under and governed by the GNU General Public jaroslav@1890: * License version 2 only, as published by the Free Software Foundation. jaroslav@1890: * However, the following notice accompanied the original version of this jaroslav@1890: * file: jaroslav@1890: * jaroslav@1890: * Written by Doug Lea with assistance from members of JCP JSR-166 jaroslav@1890: * Expert Group and released to the public domain, as explained at jaroslav@1890: * http://creativecommons.org/publicdomain/zero/1.0/ jaroslav@1890: */ jaroslav@1890: jaroslav@1890: package java.util.concurrent; jaroslav@1890: import java.util.concurrent.locks.*; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * A synchronization aid that allows a set of threads to all wait for jaroslav@1890: * each other to reach a common barrier point. CyclicBarriers are jaroslav@1890: * useful in programs involving a fixed sized party of threads that jaroslav@1890: * must occasionally wait for each other. The barrier is called jaroslav@1890: * cyclic because it can be re-used after the waiting threads jaroslav@1890: * are released. jaroslav@1890: * jaroslav@1890: *

A CyclicBarrier supports an optional {@link Runnable} command jaroslav@1890: * that is run once per barrier point, after the last thread in the party jaroslav@1890: * arrives, but before any threads are released. jaroslav@1890: * This barrier action is useful jaroslav@1890: * for updating shared-state before any of the parties continue. jaroslav@1890: * jaroslav@1890: *

Sample usage: Here is an example of jaroslav@1890: * using a barrier in a parallel decomposition design: jaroslav@1890: *

jaroslav@1890:  * class Solver {
jaroslav@1890:  *   final int N;
jaroslav@1890:  *   final float[][] data;
jaroslav@1890:  *   final CyclicBarrier barrier;
jaroslav@1890:  *
jaroslav@1890:  *   class Worker implements Runnable {
jaroslav@1890:  *     int myRow;
jaroslav@1890:  *     Worker(int row) { myRow = row; }
jaroslav@1890:  *     public void run() {
jaroslav@1890:  *       while (!done()) {
jaroslav@1890:  *         processRow(myRow);
jaroslav@1890:  *
jaroslav@1890:  *         try {
jaroslav@1890:  *           barrier.await();
jaroslav@1890:  *         } catch (InterruptedException ex) {
jaroslav@1890:  *           return;
jaroslav@1890:  *         } catch (BrokenBarrierException ex) {
jaroslav@1890:  *           return;
jaroslav@1890:  *         }
jaroslav@1890:  *       }
jaroslav@1890:  *     }
jaroslav@1890:  *   }
jaroslav@1890:  *
jaroslav@1890:  *   public Solver(float[][] matrix) {
jaroslav@1890:  *     data = matrix;
jaroslav@1890:  *     N = matrix.length;
jaroslav@1890:  *     barrier = new CyclicBarrier(N,
jaroslav@1890:  *                                 new Runnable() {
jaroslav@1890:  *                                   public void run() {
jaroslav@1890:  *                                     mergeRows(...);
jaroslav@1890:  *                                   }
jaroslav@1890:  *                                 });
jaroslav@1890:  *     for (int i = 0; i < N; ++i)
jaroslav@1890:  *       new Thread(new Worker(i)).start();
jaroslav@1890:  *
jaroslav@1890:  *     waitUntilDone();
jaroslav@1890:  *   }
jaroslav@1890:  * }
jaroslav@1890:  * 
jaroslav@1890: * Here, each worker thread processes a row of the matrix then waits at the jaroslav@1890: * barrier until all rows have been processed. When all rows are processed jaroslav@1890: * the supplied {@link Runnable} barrier action is executed and merges the jaroslav@1890: * rows. If the merger jaroslav@1890: * determines that a solution has been found then done() will return jaroslav@1890: * true and each worker will terminate. jaroslav@1890: * jaroslav@1890: *

If the barrier action does not rely on the parties being suspended when jaroslav@1890: * it is executed, then any of the threads in the party could execute that jaroslav@1890: * action when it is released. To facilitate this, each invocation of jaroslav@1890: * {@link #await} returns the arrival index of that thread at the barrier. jaroslav@1890: * You can then choose which thread should execute the barrier action, for jaroslav@1890: * example: jaroslav@1890: *

  if (barrier.await() == 0) {
jaroslav@1890:  *     // log the completion of this iteration
jaroslav@1890:  *   }
jaroslav@1890: * jaroslav@1890: *

The CyclicBarrier uses an all-or-none breakage model jaroslav@1890: * for failed synchronization attempts: If a thread leaves a barrier jaroslav@1890: * point prematurely because of interruption, failure, or timeout, all jaroslav@1890: * other threads waiting at that barrier point will also leave jaroslav@1890: * abnormally via {@link BrokenBarrierException} (or jaroslav@1890: * {@link InterruptedException} if they too were interrupted at about jaroslav@1890: * the same time). jaroslav@1890: * jaroslav@1890: *

Memory consistency effects: Actions in a thread prior to calling jaroslav@1890: * {@code await()} jaroslav@1890: * happen-before jaroslav@1890: * actions that are part of the barrier action, which in turn jaroslav@1890: * happen-before actions following a successful return from the jaroslav@1890: * corresponding {@code await()} in other threads. jaroslav@1890: * jaroslav@1890: * @since 1.5 jaroslav@1890: * @see CountDownLatch jaroslav@1890: * jaroslav@1890: * @author Doug Lea jaroslav@1890: */ jaroslav@1890: public class CyclicBarrier { jaroslav@1890: /** jaroslav@1890: * Each use of the barrier is represented as a generation instance. jaroslav@1890: * The generation changes whenever the barrier is tripped, or jaroslav@1890: * is reset. There can be many generations associated with threads jaroslav@1890: * using the barrier - due to the non-deterministic way the lock jaroslav@1890: * may be allocated to waiting threads - but only one of these jaroslav@1890: * can be active at a time (the one to which count applies) jaroslav@1890: * and all the rest are either broken or tripped. jaroslav@1890: * There need not be an active generation if there has been a break jaroslav@1890: * but no subsequent reset. jaroslav@1890: */ jaroslav@1890: private static class Generation { jaroslav@1890: boolean broken = false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** The lock for guarding barrier entry */ jaroslav@1890: private final ReentrantLock lock = new ReentrantLock(); jaroslav@1890: /** Condition to wait on until tripped */ jaroslav@1890: private final Condition trip = lock.newCondition(); jaroslav@1890: /** The number of parties */ jaroslav@1890: private final int parties; jaroslav@1890: /* The command to run when tripped */ jaroslav@1890: private final Runnable barrierCommand; jaroslav@1890: /** The current generation */ jaroslav@1890: private Generation generation = new Generation(); jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Number of parties still waiting. Counts down from parties to 0 jaroslav@1890: * on each generation. It is reset to parties on each new jaroslav@1890: * generation or when broken. jaroslav@1890: */ jaroslav@1890: private int count; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Updates state on barrier trip and wakes up everyone. jaroslav@1890: * Called only while holding lock. jaroslav@1890: */ jaroslav@1890: private void nextGeneration() { jaroslav@1890: // signal completion of last generation jaroslav@1890: trip.signalAll(); jaroslav@1890: // set up next generation jaroslav@1890: count = parties; jaroslav@1890: generation = new Generation(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Sets current barrier generation as broken and wakes up everyone. jaroslav@1890: * Called only while holding lock. jaroslav@1890: */ jaroslav@1890: private void breakBarrier() { jaroslav@1890: generation.broken = true; jaroslav@1890: count = parties; jaroslav@1890: trip.signalAll(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Main barrier code, covering the various policies. jaroslav@1890: */ jaroslav@1890: private int dowait(boolean timed, long nanos) jaroslav@1890: throws InterruptedException, BrokenBarrierException, jaroslav@1890: TimeoutException { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: final Generation g = generation; jaroslav@1890: jaroslav@1890: if (g.broken) jaroslav@1890: throw new BrokenBarrierException(); jaroslav@1890: jaroslav@1890: if (Thread.interrupted()) { jaroslav@1890: breakBarrier(); jaroslav@1890: throw new InterruptedException(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: int index = --count; jaroslav@1890: if (index == 0) { // tripped jaroslav@1890: boolean ranAction = false; jaroslav@1890: try { jaroslav@1890: final Runnable command = barrierCommand; jaroslav@1890: if (command != null) jaroslav@1890: command.run(); jaroslav@1890: ranAction = true; jaroslav@1890: nextGeneration(); jaroslav@1890: return 0; jaroslav@1890: } finally { jaroslav@1890: if (!ranAction) jaroslav@1890: breakBarrier(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: // loop until tripped, broken, interrupted, or timed out jaroslav@1890: for (;;) { jaroslav@1890: try { jaroslav@1890: if (!timed) jaroslav@1890: trip.await(); jaroslav@1890: else if (nanos > 0L) jaroslav@1890: nanos = trip.awaitNanos(nanos); jaroslav@1890: } catch (InterruptedException ie) { jaroslav@1890: if (g == generation && ! g.broken) { jaroslav@1890: breakBarrier(); jaroslav@1890: throw ie; jaroslav@1890: } else { jaroslav@1890: // We're about to finish waiting even if we had not jaroslav@1890: // been interrupted, so this interrupt is deemed to jaroslav@1890: // "belong" to subsequent execution. jaroslav@1890: Thread.currentThread().interrupt(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: if (g.broken) jaroslav@1890: throw new BrokenBarrierException(); jaroslav@1890: jaroslav@1890: if (g != generation) jaroslav@1890: return index; jaroslav@1890: jaroslav@1890: if (timed && nanos <= 0L) { jaroslav@1890: breakBarrier(); jaroslav@1890: throw new TimeoutException(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a new CyclicBarrier that will trip when the jaroslav@1890: * given number of parties (threads) are waiting upon it, and which jaroslav@1890: * will execute the given barrier action when the barrier is tripped, jaroslav@1890: * performed by the last thread entering the barrier. jaroslav@1890: * jaroslav@1890: * @param parties the number of threads that must invoke {@link #await} jaroslav@1890: * before the barrier is tripped jaroslav@1890: * @param barrierAction the command to execute when the barrier is jaroslav@1890: * tripped, or {@code null} if there is no action jaroslav@1890: * @throws IllegalArgumentException if {@code parties} is less than 1 jaroslav@1890: */ jaroslav@1890: public CyclicBarrier(int parties, Runnable barrierAction) { jaroslav@1890: if (parties <= 0) throw new IllegalArgumentException(); jaroslav@1890: this.parties = parties; jaroslav@1890: this.count = parties; jaroslav@1890: this.barrierCommand = barrierAction; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a new CyclicBarrier that will trip when the jaroslav@1890: * given number of parties (threads) are waiting upon it, and jaroslav@1890: * does not perform a predefined action when the barrier is tripped. jaroslav@1890: * jaroslav@1890: * @param parties the number of threads that must invoke {@link #await} jaroslav@1890: * before the barrier is tripped jaroslav@1890: * @throws IllegalArgumentException if {@code parties} is less than 1 jaroslav@1890: */ jaroslav@1890: public CyclicBarrier(int parties) { jaroslav@1890: this(parties, null); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the number of parties required to trip this barrier. jaroslav@1890: * jaroslav@1890: * @return the number of parties required to trip this barrier jaroslav@1890: */ jaroslav@1890: public int getParties() { jaroslav@1890: return parties; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Waits until all {@linkplain #getParties parties} have invoked jaroslav@1890: * await on this barrier. jaroslav@1890: * jaroslav@1890: *

If the current thread is not the last to arrive then it is jaroslav@1890: * disabled for thread scheduling purposes and lies dormant until jaroslav@1890: * one of the following things happens: jaroslav@1890: *

jaroslav@1890: * jaroslav@1890: *

If the current thread: jaroslav@1890: *

jaroslav@1890: * then {@link InterruptedException} is thrown and the current thread's jaroslav@1890: * interrupted status is cleared. jaroslav@1890: * jaroslav@1890: *

If the barrier is {@link #reset} while any thread is waiting, jaroslav@1890: * or if the barrier {@linkplain #isBroken is broken} when jaroslav@1890: * await is invoked, or while any thread is waiting, then jaroslav@1890: * {@link BrokenBarrierException} is thrown. jaroslav@1890: * jaroslav@1890: *

If any thread is {@linkplain Thread#interrupt interrupted} while waiting, jaroslav@1890: * then all other waiting threads will throw jaroslav@1890: * {@link BrokenBarrierException} and the barrier is placed in the broken jaroslav@1890: * state. jaroslav@1890: * jaroslav@1890: *

If the current thread is the last thread to arrive, and a jaroslav@1890: * non-null barrier action was supplied in the constructor, then the jaroslav@1890: * current thread runs the action before allowing the other threads to jaroslav@1890: * continue. jaroslav@1890: * If an exception occurs during the barrier action then that exception jaroslav@1890: * will be propagated in the current thread and the barrier is placed in jaroslav@1890: * the broken state. jaroslav@1890: * jaroslav@1890: * @return the arrival index of the current thread, where index jaroslav@1890: * {@link #getParties()} - 1 indicates the first jaroslav@1890: * to arrive and zero indicates the last to arrive jaroslav@1890: * @throws InterruptedException if the current thread was interrupted jaroslav@1890: * while waiting jaroslav@1890: * @throws BrokenBarrierException if another thread was jaroslav@1890: * interrupted or timed out while the current thread was jaroslav@1890: * waiting, or the barrier was reset, or the barrier was jaroslav@1890: * broken when {@code await} was called, or the barrier jaroslav@1890: * action (if present) failed due an exception. jaroslav@1890: */ jaroslav@1890: public int await() throws InterruptedException, BrokenBarrierException { jaroslav@1890: try { jaroslav@1890: return dowait(false, 0L); jaroslav@1890: } catch (TimeoutException toe) { jaroslav@1890: throw new Error(toe); // cannot happen; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Waits until all {@linkplain #getParties parties} have invoked jaroslav@1890: * await on this barrier, or the specified waiting time elapses. jaroslav@1890: * jaroslav@1890: *

If the current thread is not the last to arrive then it is jaroslav@1890: * disabled for thread scheduling purposes and lies dormant until jaroslav@1890: * one of the following things happens: jaroslav@1890: *

jaroslav@1890: * jaroslav@1890: *

If the current thread: jaroslav@1890: *

jaroslav@1890: * then {@link InterruptedException} is thrown and the current thread's jaroslav@1890: * interrupted status is cleared. jaroslav@1890: * jaroslav@1890: *

If the specified waiting time elapses then {@link TimeoutException} jaroslav@1890: * is thrown. If the time is less than or equal to zero, the jaroslav@1890: * method will not wait at all. jaroslav@1890: * jaroslav@1890: *

If the barrier is {@link #reset} while any thread is waiting, jaroslav@1890: * or if the barrier {@linkplain #isBroken is broken} when jaroslav@1890: * await is invoked, or while any thread is waiting, then jaroslav@1890: * {@link BrokenBarrierException} is thrown. jaroslav@1890: * jaroslav@1890: *

If any thread is {@linkplain Thread#interrupt interrupted} while jaroslav@1890: * waiting, then all other waiting threads will throw {@link jaroslav@1890: * BrokenBarrierException} and the barrier is placed in the broken jaroslav@1890: * state. jaroslav@1890: * jaroslav@1890: *

If the current thread is the last thread to arrive, and a jaroslav@1890: * non-null barrier action was supplied in the constructor, then the jaroslav@1890: * current thread runs the action before allowing the other threads to jaroslav@1890: * continue. jaroslav@1890: * If an exception occurs during the barrier action then that exception jaroslav@1890: * will be propagated in the current thread and the barrier is placed in jaroslav@1890: * the broken state. jaroslav@1890: * jaroslav@1890: * @param timeout the time to wait for the barrier jaroslav@1890: * @param unit the time unit of the timeout parameter jaroslav@1890: * @return the arrival index of the current thread, where index jaroslav@1890: * {@link #getParties()} - 1 indicates the first jaroslav@1890: * to arrive and zero indicates the last to arrive jaroslav@1890: * @throws InterruptedException if the current thread was interrupted jaroslav@1890: * while waiting jaroslav@1890: * @throws TimeoutException if the specified timeout elapses jaroslav@1890: * @throws BrokenBarrierException if another thread was jaroslav@1890: * interrupted or timed out while the current thread was jaroslav@1890: * waiting, or the barrier was reset, or the barrier was broken jaroslav@1890: * when {@code await} was called, or the barrier action (if jaroslav@1890: * present) failed due an exception jaroslav@1890: */ jaroslav@1890: public int await(long timeout, TimeUnit unit) jaroslav@1890: throws InterruptedException, jaroslav@1890: BrokenBarrierException, jaroslav@1890: TimeoutException { jaroslav@1890: return dowait(true, unit.toNanos(timeout)); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Queries if this barrier is in a broken state. jaroslav@1890: * jaroslav@1890: * @return {@code true} if one or more parties broke out of this jaroslav@1890: * barrier due to interruption or timeout since jaroslav@1890: * construction or the last reset, or a barrier action jaroslav@1890: * failed due to an exception; {@code false} otherwise. jaroslav@1890: */ jaroslav@1890: public boolean isBroken() { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: return generation.broken; jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Resets the barrier to its initial state. If any parties are jaroslav@1890: * currently waiting at the barrier, they will return with a jaroslav@1890: * {@link BrokenBarrierException}. Note that resets after jaroslav@1890: * a breakage has occurred for other reasons can be complicated to jaroslav@1890: * carry out; threads need to re-synchronize in some other way, jaroslav@1890: * and choose one to perform the reset. It may be preferable to jaroslav@1890: * instead create a new barrier for subsequent use. jaroslav@1890: */ jaroslav@1890: public void reset() { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: breakBarrier(); // break the current generation jaroslav@1890: nextGeneration(); // start a new generation jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the number of parties currently waiting at the barrier. jaroslav@1890: * This method is primarily useful for debugging and assertions. jaroslav@1890: * jaroslav@1890: * @return the number of parties currently blocked in {@link #await} jaroslav@1890: */ jaroslav@1890: public int getNumberWaiting() { jaroslav@1890: final ReentrantLock lock = this.lock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: return parties - count; jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: }