# CyclicBarrier

public class **CyclicBarrier** extends [Object](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html)  
A synchronization aid that allows a set of threads to all wait for
each other to reach a common barrier point. CyclicBarriers are
useful in programs involving a fixed sized party of threads that
must occasionally wait for each other. The barrier is called
*cyclic* because it can be re-used after the waiting threads
are released.

A `CyclicBarrier` supports an optional `https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Runnable.html` command
that is run once per barrier point, after the last thread in the party
arrives, but before any threads are released.
This *barrier action* is useful
for updating shared-state before any of the parties continue.

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

     class Solver {
       final int N;
       final float[][] data;
       final CyclicBarrier barrier;

       class Worker implements Runnable {
         int myRow;
         Worker(int row) { myRow = row; }
         public void run() {
           while (!done()) {
             processRow(myRow);

             try {
               barrier.await();
             } catch (InterruptedException ex) {
               return;
             } catch (BrokenBarrierException ex) {
               return;
             }
           }
         }
       }

       public Solver(float[][] matrix) {
         data = matrix;
         N = matrix.length;
         Runnable barrierAction =
           new Runnable() { public void run() { mergeRows(...); }};
         barrier = new CyclicBarrier(N, barrierAction);

         List<Thread> threads = new ArrayList<>(N);
         for (int i = 0; i < N; i++) {
           Thread thread = new Thread(new Worker(i));
           threads.add(thread);
           thread.start();
         }

         // wait until done
         for (Thread thread : threads)
           thread.join();
       }
     }

Here, each worker thread processes a row of the matrix then waits at the barrier until all rows have been processed. When all rows are processed the supplied `https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Runnable.html` barrier action is executed and merges the rows. If the merger determines that a solution has been found then `done()` will return `true` and each worker will terminate.

If the barrier action does not rely on the parties being suspended when
it is executed, then any of the threads in the party could execute that
action when it is released. To facilitate this, each invocation of
`https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#await()` returns the arrival index of that thread at the barrier.
You can then choose which thread should execute the barrier action, for
example:

     if (barrier.await() == 0) {
       // log the completion of this iteration
     }

The `CyclicBarrier` uses an all-or-none breakage model
for failed synchronization attempts: If a thread leaves a barrier
point prematurely because of interruption, failure, or timeout, all
other threads waiting at that barrier point will also leave
abnormally via `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/BrokenBarrierException.html` (or
`https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/InterruptedException.html` if they too were interrupted at about
the same time).

Memory consistency effects: Actions in a thread prior to calling
`await()`
[*happen-before*](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/package-summary#MemoryVisibility)
actions that are part of the barrier action, which in turn
*happen-before* actions following a successful return from the
corresponding `await()` in other threads.

##### See Also

- `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CountDownLatch.html`

### Public Constructor Summary

|---|---|
|   | [CyclicBarrier](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#CyclicBarrier(int,%20java.lang.Runnable))(int parties, [Runnable](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Runnable.html) barrierAction) Creates a new `CyclicBarrier` that will trip when the given number of parties (threads) are waiting upon it, and which will execute the given barrier action when the barrier is tripped, performed by the last thread entering the barrier. |
|   | [CyclicBarrier](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#CyclicBarrier(int))(int parties) Creates a new `CyclicBarrier` that will trip when the given number of parties (threads) are waiting upon it, and does not perform a predefined action when the barrier is tripped. |

### Public Method Summary

|---|---|
| int | [await](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#await())() Waits until all {@linkplain #getParties parties} have invoked `await` on this barrier. |
| int | [await](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#await(long,%20java.util.concurrent.TimeUnit))(long timeout, [TimeUnit](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/TimeUnit.html) unit) Waits until all {@linkplain #getParties parties} have invoked `await` on this barrier, or the specified waiting time elapses. |
| int | [getNumberWaiting](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#getNumberWaiting())() Returns the number of parties currently waiting at the barrier. |
| int | [getParties](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#getParties())() Returns the number of parties required to trip this barrier. |
| boolean | [isBroken](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#isBroken())() Queries if this barrier is in a broken state. |
| void | [reset](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#reset())() Resets the barrier to its initial state. |

### Inherited Method Summary

From class [java.lang.Object](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html)

|---|---|
| [Object](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html) | [clone](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#clone())() Creates and returns a copy of this `Object`. |
| boolean | [equals](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#equals(java.lang.Object))([Object](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html) obj) Compares this instance with the specified object and indicates if they are equal. |
| void | [finalize](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#finalize())() Invoked when the garbage collector has detected that this instance is no longer reachable. |
| final [Class](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Class.html)\<?\> | [getClass](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#getClass())() Returns the unique instance of `https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Class.html` that represents this object's class. |
| int | [hashCode](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#hashCode())() Returns an integer hash code for this object. |
| final void | [notify](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#notify())() Causes a thread which is waiting on this object's monitor (by means of calling one of the `wait()` methods) to be woken up. |
| final void | [notifyAll](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#notifyAll())() Causes all threads which are waiting on this object's monitor (by means of calling one of the `wait()` methods) to be woken up. |
| [String](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/String.html) | [toString](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#toString())() Returns a string containing a concise, human-readable description of this object. |
| final void | [wait](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#wait(long,%20int))(long timeout, int nanos) Causes the calling thread to wait until another thread calls the `notify()` or `notifyAll()` method of this object or until the specified timeout expires. |
| final void | [wait](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#wait(long))(long timeout) Causes the calling thread to wait until another thread calls the `notify()` or `notifyAll()` method of this object or until the specified timeout expires. |
| final void | [wait](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Object.html#wait())() Causes the calling thread to wait until another thread calls the `notify()` or `notifyAll()` method of this object. |

## Public Constructors

#### public
**CyclicBarrier**
(int parties, [Runnable](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/Runnable.html) barrierAction)

Creates a new `CyclicBarrier` that will trip when the
given number of parties (threads) are waiting upon it, and which
will execute the given barrier action when the barrier is tripped,
performed by the last thread entering the barrier.

##### Parameters

| parties | the number of threads that must invoke `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#await()` before the barrier is tripped |
| barrierAction | the command to execute when the barrier is tripped, or `null` if there is no action |
|---|---|

##### Throws

| [IllegalArgumentException](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/IllegalArgumentException.html) | if `parties` is less than 1 |
|---|---|

#### public
**CyclicBarrier**
(int parties)

Creates a new `CyclicBarrier` that will trip when the
given number of parties (threads) are waiting upon it, and
does not perform a predefined action when the barrier is tripped.

##### Parameters

| parties | the number of threads that must invoke `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#await()` before the barrier is tripped |
|---|---|

##### Throws

| [IllegalArgumentException](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/IllegalArgumentException.html) | if `parties` is less than 1 |
|---|---|

## Public Methods

#### public int
**await**
()

Waits until all {@linkplain #getParties parties} have invoked
`await` on this barrier.

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

- The last thread arrives; or
- Some other thread {@linkplain Thread#interrupt interrupts} the current thread; or
- Some other thread {@linkplain Thread#interrupt interrupts} one of the other waiting threads; or
- Some other thread times out while waiting for barrier; or
- Some other thread invokes `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#reset()` on this barrier.

If the current thread:

- has its interrupted status set on entry to this method; or
- is {@linkplain Thread#interrupt interrupted} while waiting

then `https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/InterruptedException.html` is thrown and the current thread's interrupted status is cleared.

If the barrier is `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#reset()` while any thread is waiting,
or if the barrier {@linkplain #isBroken is broken} when
`await` is invoked, or while any thread is waiting, then
`https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/BrokenBarrierException.html` is thrown.

If any thread is {@linkplain Thread#interrupt interrupted} while waiting,
then all other waiting threads will throw
`https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/BrokenBarrierException.html` and the barrier is placed in the broken
state.

If the current thread is the last thread to arrive, and a
non-null barrier action was supplied in the constructor, then the
current thread runs the action before allowing the other threads to
continue.
If an exception occurs during the barrier action then that exception
will be propagated in the current thread and the barrier is placed in
the broken state.

##### Returns

- the arrival index of the current thread, where index `getParties() - 1` indicates the first to arrive and zero indicates the last to arrive

##### Throws

| [InterruptedException](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/InterruptedException.html) | if the current thread was interrupted while waiting |
| [BrokenBarrierException](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/BrokenBarrierException.html) | if *another* thread was interrupted or timed out while the current thread was waiting, or the barrier was reset, or the barrier was broken when `await` was called, or the barrier action (if present) failed due to an exception |
|---|---|

#### public int
**await**
(long timeout, [TimeUnit](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/TimeUnit.html) unit)

Waits until all {@linkplain #getParties parties} have invoked
`await` on this barrier, or the specified waiting time elapses.

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

- The last thread arrives; or
- The specified timeout elapses; or
- Some other thread {@linkplain Thread#interrupt interrupts} the current thread; or
- Some other thread {@linkplain Thread#interrupt interrupts} one of the other waiting threads; or
- Some other thread times out while waiting for barrier; or
- Some other thread invokes `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#reset()` on this barrier.

If the current thread:

- has its interrupted status set on entry to this method; or
- is {@linkplain Thread#interrupt interrupted} while waiting

then `https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/InterruptedException.html` is thrown and the current thread's interrupted status is cleared.

If the specified waiting time elapses then `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/TimeoutException.html`
is thrown. If the time is less than or equal to zero, the
method will not wait at all.

If the barrier is `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#reset()` while any thread is waiting,
or if the barrier {@linkplain #isBroken is broken} when
`await` is invoked, or while any thread is waiting, then
`https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/BrokenBarrierException.html` is thrown.

If any thread is {@linkplain Thread#interrupt interrupted} while
waiting, then all other waiting threads will throw `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/BrokenBarrierException.html` and the barrier is placed in the broken
state.

If the current thread is the last thread to arrive, and a
non-null barrier action was supplied in the constructor, then the
current thread runs the action before allowing the other threads to
continue.
If an exception occurs during the barrier action then that exception
will be propagated in the current thread and the barrier is placed in
the broken state.

##### Parameters

| timeout | the time to wait for the barrier |
| unit | the time unit of the timeout parameter |
|---|---|

##### Returns

- the arrival index of the current thread, where index `getParties() - 1` indicates the first to arrive and zero indicates the last to arrive

##### Throws

| [InterruptedException](https://developers.google.com/j2objc/javadoc/jre/reference/java/lang/InterruptedException.html) | if the current thread was interrupted while waiting |
| [TimeoutException](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/TimeoutException.html) | if the specified timeout elapses. In this case the barrier will be broken. |
| [BrokenBarrierException](https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/BrokenBarrierException.html) | if *another* thread was interrupted or timed out while the current thread was waiting, or the barrier was reset, or the barrier was broken when `await` was called, or the barrier action (if present) failed due to an exception |
|---|---|

#### public int
**getNumberWaiting**
()

Returns the number of parties currently waiting at the barrier.
This method is primarily useful for debugging and assertions.

##### Returns

- the number of parties currently blocked in `https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/CyclicBarrier.html#await()`

#### public int
**getParties**
()

Returns the number of parties required to trip this barrier.

##### Returns

- the number of parties required to trip this barrier

#### public boolean
**isBroken**
()

Queries if this barrier is in a broken state.

##### Returns

- `true` if one or more parties broke out of this barrier due to interruption or timeout since construction or the last reset, or a barrier action failed due to an exception; `false` otherwise.

#### public void
**reset**
()

Resets the barrier to its initial state. If any parties are
currently waiting at the barrier, they will return with a
`https://developers.google.com/j2objc/javadoc/jre/reference/java/util/concurrent/BrokenBarrierException.html`. Note that resets *after*
a breakage has occurred for other reasons can be complicated to
carry out; threads need to re-synchronize in some other way,
and choose one to perform the reset. It may be preferable to
instead create a new barrier for subsequent use.