@ParametersAreNonnullByDefault public class Barrier extends Object
Barrier
.
A Barrier can be used to block and wait for the completion of a given set of promises. A barrier should only be used once and after a call to await, no further promises should be added. Also await must only be called once.
The general call pattern looks like that:
Barrier b = Barrier.create();
b.add(somePromise);
b.add(anotherPromise);
b.await(1, TimeUnit.MINUTE);
Always prefer await(long, java.util.concurrent.TimeUnit)
and specify a sane timeout since something
might always go wrong and a promise might therefore not complete (in time - or not at all) and your program
is locked forever.
This barrier can also be used in a non-blocking way, by calling asFuture()
after the last call to
add(Promise)
. If possible, the non-block approach should always be preferred.
Constructor and Description |
---|
Barrier() |
Modifier and Type | Method and Description |
---|---|
void |
add(Promise<?> promise)
Adds a promise to the barrier which will be waited for.
|
Future |
asFuture()
Generates a new
Future which completes if the las added promise completes or if any one of those fails. |
void |
await()
Waits until all previously added promises completed (either successfully or failed).
|
boolean |
await(long time,
TimeUnit unit)
Waits until all previously added promises completed or the given timeout expires.
|
static Barrier |
create()
Creates a new barrier.
|
public static Barrier create()
public void add(Promise<?> promise)
Note that one must not call add after calling await.
promise
- the promise to wait forpublic Future asFuture()
Future
which completes if the las added promise completes or if any one of those fails.public void await() throws InterruptedException
Note that this method might block for an indefinite amount of time. Consider using
await(long, java.util.concurrent.TimeUnit)
and specify a sane timeout
InterruptedException
- if the thread was interrupted while waiting for completion.public boolean await(long time, TimeUnit unit)
time
- the number of time intervals to wait for completionunit
- the unit of time intervals to wait for completionCopyright © 2018. All rights reserved.