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