Phaser class.
A CyclicBarrier supports an optional Runnable 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 = () -> 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)
try {
thread.join();
} catch (InterruptedException ex) { }
}
}
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 Runnable 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
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 BrokenBarrierException (or
InterruptedException if they too were interrupted at about
the same time).
Memory consistency effects: Actions in a thread prior to calling
await()
happen-before
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.
CountDownLatch, Phaser
| Modifier and Type | Class and Description |
|---|---|
| private static class | CyclicBarrier.
Each use of the barrier is represented as a generation instance. |
| Modifier and Type | Field and Description |
|---|---|
| private final Runnable | barrierCommand
The command to run when tripped |
| private int | count
Number of parties still waiting. |
| private CyclicBarrier. | generation
The current generation |
| private final ReentrantLock | lock
The lock for guarding barrier entry |
| private final int | parties
The number of parties |
| private final Condition | trip
Condition to wait on until tripped |
| Access | Constructor and Description |
|---|---|
| public | CyclicBarrier(int
the number of threads that must invoke parties, Runnable await
before the barrier is trippedthe command to execute when the barrier is
tripped, or barrierAction)null if there is no actionCreates a new |
| public | CyclicBarrier(int
the number of threads that must invoke parties)await
before the barrier is trippedCreates a new |
| Modifier and Type | Method and Description |
|---|---|
| public int | |
| public int | Returns: the arrival index of the current thread, where indexgetParties() - 1 indicates the first
to arrive and zero indicates the last to arrivethe time to wait for the barrier timeout, TimeUnit the time unit of the timeout parameter unit)Waits until all parties have invoked
|
| private void | |
| private int | |
| public int | Returns: the number of parties currently blocked inawaitReturns the number of parties currently waiting at the barrier. |
| public int | Returns: the number of parties required to trip this barrierReturns the number of parties required to trip this barrier. |
| public boolean | 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.Queries if this barrier is in a broken state. |
| private void | |
| public void |
| barrierCommand | back to summary |
|---|---|
| private final Runnable barrierCommand The command to run when tripped | |
| count | back to summary |
|---|---|
| private int count Number of parties still waiting. Counts down from parties to 0 on each generation. It is reset to parties on each new generation or when broken. | |
| generation | back to summary |
|---|---|
| private CyclicBarrier. The current generation | |
| lock | back to summary |
|---|---|
| private final ReentrantLock lock The lock for guarding barrier entry | |
| parties | back to summary |
|---|---|
| private final int parties The number of parties | |
| trip | back to summary |
|---|---|
| private final Condition trip Condition to wait on until tripped | |
| CyclicBarrier | back to summary |
|---|---|
| public CyclicBarrier(int parties, Runnable barrierAction) Creates a new
| |
| CyclicBarrier | back to summary |
|---|---|
| public CyclicBarrier(int parties) Creates a new
| |
| await | back to summary |
|---|---|
| public int await() throws InterruptedException, BrokenBarrierException Waits until all parties have invoked
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:
If the current thread:
InterruptedException is thrown and the current thread's
interrupted status is cleared.
If the barrier is If any thread is interrupted while waiting,
then all other waiting threads will throw
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.
| |
| await | back to summary |
|---|---|
| public int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException Waits until all parties have invoked
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:
If the current thread:
InterruptedException is thrown and the current thread's
interrupted status is cleared.
If the specified waiting time elapses then If the barrier is If any thread is interrupted while
waiting, then all other waiting threads will throw 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.
| |
| breakBarrier | back to summary |
|---|---|
| private void breakBarrier() Sets current barrier generation as broken and wakes up everyone. Called only while holding lock. | |
| dowait | back to summary |
|---|---|
| private int dowait(boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException Main barrier code, covering the various policies. | |
| getNumberWaiting | back to summary |
|---|---|
| public int getNumberWaiting() Returns the number of parties currently waiting at the barrier. This method is primarily useful for debugging and assertions.
| |
| getParties | back to summary |
|---|---|
| public int getParties() Returns the number of parties required to trip this barrier.
| |
| isBroken | back to summary |
|---|---|
| public boolean isBroken() Queries if this barrier is in a broken state.
| |
| nextGeneration | back to summary |
|---|---|
| private void nextGeneration() Updates state on barrier trip and wakes up everyone. Called only while holding lock. | |
| reset | back to summary |
|---|---|
| public void reset() Resets the barrier to its initial state. If any parties are
currently waiting at the barrier, they will return with a
| |
count applies)
and all the rest are either broken or tripped.
There need not be an active generation if there has been a break
but no subsequent reset.
| Modifier and Type | Field and Description |
|---|---|
| pack-priv boolean |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| broken | back to summary |
|---|---|
| pack-priv boolean broken | |
| Generation | back to summary |
|---|---|
| pack-priv Generation() | |