下面列出了java.util.concurrent.CompletableFuture#anyOf ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* anyOf result completes exceptionally when any component does.
*/
public void testAnyOf_exceptional() throws Exception {
for (int k = 0; k < 10; k++) {
CompletableFuture[] fs = new CompletableFuture[k];
CFException[] exs = new CFException[k];
for (int i = 0; i < k; i++) {
fs[i] = new CompletableFuture<>();
exs[i] = new CFException();
}
CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
checkIncomplete(f);
for (int i = 0; i < k; i++) {
fs[i].completeExceptionally(exs[i]);
checkCompletedWithWrappedException(f, exs[0]);
checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
}
}
}
/**
* anyOf returns a future completed normally with a value when
* a component future does
*/
public void testAnyOf_normal() throws Exception {
for (int k = 0; k < 10; k++) {
CompletableFuture[] fs = new CompletableFuture[k];
for (int i = 0; i < k; i++)
fs[i] = new CompletableFuture<>();
CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
checkIncomplete(f);
for (int i = 0; i < k; i++) {
fs[i].complete(i);
checkCompletedNormally(f, 0);
int x = (int) CompletableFuture.anyOf(fs).join();
assertTrue(0 <= x && x <= i);
}
}
}
/**
* CompletableFuture.anyOf adds a completion handler to every future its passed so if we call it
* too often we can quickly wind up with thousands of completion handlers which take a long time
* to iterate through and notify. So only create it when the futures it covers have actually
* changed.
*/
@SuppressWarnings("rawtypes")
private void updateNextOutputAvailableFuture() {
if (preserveOrder) {
nextOutputAvailableFuture = inProgress.isEmpty() ? completedFuture(null) : inProgress.get(0);
} else {
nextOutputAvailableFuture =
CompletableFuture.anyOf(inProgress.toArray(new CompletableFuture[0]));
}
}
/**
* anyOf(no component futures) returns an incomplete future
*/
public void testAnyOf_empty() throws Exception {
for (Integer v1 : new Integer[] { 1, null })
{
CompletableFuture<Object> f = CompletableFuture.anyOf();
checkIncomplete(f);
f.complete(v1);
checkCompletedNormally(f, v1);
}}
@Test
public void anyOf() throws ExecutionException, InterruptedException {
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "Future");
CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> " is awesome!");
CompletableFuture<String> cf3 = CompletableFuture.supplyAsync(() -> "!");
CompletableFuture<Object> anyCf = CompletableFuture.anyOf(cf1, cf2, cf3);
System.out.println(anyCf.get());
assertThat(anyCf).isDone();
}
/**
* Asynchronously starts checking readiness of servers of a machine. Method {@link #await()} waits
* the result of this asynchronous check.
*
* @param serverReadinessHandler consumer which will be called with server reference as the
* argument when server become available
* @throws InternalInfrastructureException if check of a server failed due to an unexpected error
* @throws InfrastructureException if check of a server failed due to an error
*/
public CompletableFuture<?> startAsync(Consumer<String> serverReadinessHandler)
throws InfrastructureException {
timer = new Timer("ServersChecker", true);
List<ServerChecker> serverCheckers = getServerCheckers();
// should be completed with an exception if a server considered unavailable
CompletableFuture<Void> firstNonAvailable = new CompletableFuture<>();
CompletableFuture[] checkTasks =
serverCheckers
.stream()
.map(ServerChecker::getReportCompFuture)
.map(
compFut ->
compFut
.thenAccept(serverReadinessHandler)
.exceptionally(
e -> {
// cleanup checkers tasks
timer.cancel();
firstNonAvailable.completeExceptionally(e);
return null;
}))
.toArray(CompletableFuture[]::new);
resultTimeoutSeconds = checkTasks.length * 180;
// should complete when all servers checks reported availability
CompletableFuture<Void> allAvailable = CompletableFuture.allOf(checkTasks);
// should complete when all servers are available or any server is unavailable
result = CompletableFuture.anyOf(allAvailable, firstNonAvailable);
for (ServerChecker serverChecker : serverCheckers) {
serverChecker.start();
}
return result;
}
/**
* 保证确有一个Future执行完毕
*
* @param futures
* @return
*/
public static <T> CompletableFuture<Object> anyOf(final Collection<CompletableFuture<T>> futures) {
int size = futures.size();
switch (size) {
case 0:
return CompletableFuture.completedFuture(null);
case 1:
return futures.iterator().next().thenApply(o -> o);
default:
return CompletableFuture.anyOf(futures.toArray(new CompletableFuture[futures.size()]));
}
}
/**
* React to the completion of any of the events in the previous stage. Will not work reliably with Streams
* where filter has been applied in earlier stages. (As Filter completes the Stream for events that are filtered out, they
* potentially shortcircuit the completion of the stage).
*
* @param fn Function to applyHKT when any of the previous events complete
* @return Next stage in the stream
*/
default <R> SimpleReactStream<R> anyOf(final Function<? super U, ? extends R> fn) {
final CompletableFuture[] array = lastActiveArray(getLastActive());
final CompletableFuture cf = CompletableFuture.anyOf(array);
final CompletableFuture onSuccess = cf.thenApplyAsync(fn, getTaskExecutor());
return (SimpleReactStream<R>) withLastActive(new EagerStreamWrapper(
onSuccess, getErrorHandler()));
}
@Override
public CompletableFuture<?> request(String method, Object parameter) {
// Check the registered method handlers
Function<Object, CompletableFuture<Object>> handler = methodHandlers.get(method);
if (handler != null) {
return handler.apply(parameter);
}
// Ask the delegate objects whether they can handle the request generically
List<CompletableFuture<?>> futures = new ArrayList<>(delegates.size());
for (Object delegate : delegates) {
if (delegate instanceof Endpoint) {
futures.add(((Endpoint) delegate).request(method, parameter));
}
}
if (!futures.isEmpty()) {
return CompletableFuture.anyOf(futures.toArray(new CompletableFuture[futures.size()]));
}
// Create a log message about the unsupported method
String message = "Unsupported request method: " + method;
if (isOptionalMethod(method)) {
LOG.log(Level.INFO, message);
return CompletableFuture.completedFuture(null);
}
LOG.log(Level.WARNING, message);
CompletableFuture<?> exceptionalResult = new CompletableFuture<Object>();
ResponseError error = new ResponseError(ResponseErrorCode.MethodNotFound, message, null);
exceptionalResult.completeExceptionally(new ResponseErrorException(error));
return exceptionalResult;
}
public void testAnyOf_normal_backwards() throws Exception {
for (int k = 0; k < 10; k++) {
CompletableFuture[] fs = new CompletableFuture[k];
for (int i = 0; i < k; i++)
fs[i] = new CompletableFuture<>();
CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
checkIncomplete(f);
for (int i = k - 1; i >= 0; i--) {
fs[i].complete(i);
checkCompletedNormally(f, k - 1);
int x = (int) CompletableFuture.anyOf(fs).join();
assertTrue(i <= x && x <= k - 1);
}
}
}
/**
* @return Combine two CompletableFuture's by taking the first present
*/
static <T> Semigroup<CompletableFuture<T>> firstCompleteCompletableFuture() {
return (a, b) -> (CompletableFuture<T>)CompletableFuture.<T>anyOf(a,b);
}
/**
* Returns a new CompletableFuture that is completed when any of the given CompletableFutures complete, with the
* same result. Otherwise, if it completed exceptionally, the returned CompletableFuture also does so, with a
* CompletionException holding this exception as its cause. If no CompletableFutures are provided, returns an
* incomplete CompletableFuture.
* <p>
* Unlike the original {@link CompletableFuture#allOf(CompletableFuture[])} this method invokes the dependent
* stages into the Vert.x context.
*
* @param context the context
* @param futures the CompletableFutures
* @return a new CompletableFuture that is completed with the result or exception of any of the given
* CompletableFutures when one completes
* @throws NullPointerException if the array or any of its elements are {@code null}
*/
public static VertxCompletableFuture<Object> anyOf(Context context, CompletableFuture<?>... futures) {
CompletableFuture<Object> all = CompletableFuture.anyOf(futures);
return VertxCompletableFuture.from(context, all);
}
/**
* Returns a new CompletableFuture that is completed when any of the given CompletableFutures complete, with the
* same result. Otherwise, if it completed exceptionally, the returned CompletableFuture also does so, with a
* CompletionException holding this exception as its cause. If no CompletableFutures are provided, returns an
* incomplete CompletableFuture.
* <p>
* Unlike the original {@link CompletableFuture#allOf(CompletableFuture[])} this method invokes the dependent
* stages into the Vert.x context.
*
* @param context the context
* @param futures the CompletableFutures
* @return a new CompletableFuture that is completed with the result or exception of any of the given
* CompletableFutures when one completes
* @throws NullPointerException if the array or any of its elements are {@code null}
*/
public static VertxCompletableFuture<Object> anyOf(Context context, CompletableFuture<?>... futures) {
CompletableFuture<Object> all = CompletableFuture.anyOf(futures);
return VertxCompletableFuture.from(context, all);
}
/**
* Returns a new CompletableFuture that is completed when any of the given CompletableFutures complete, with the
* same result. Otherwise, if it completed exceptionally, the returned CompletableFuture also does so, with a
* CompletionException holding this exception as its cause. If no CompletableFutures are provided, returns an
* incomplete CompletableFuture.
* <p>
* Unlike the original {@link CompletableFuture#allOf(CompletableFuture[])} this method invokes the dependent
* stages into the Vert.x context.
*
* @param vertx the Vert.x instance to retrieve the context
* @param futures the CompletableFutures
* @return a new CompletableFuture that is completed with the result or exception of any of the given
* CompletableFutures when one completes
* @throws NullPointerException if the array or any of its elements are {@code null}
*/
public static VertxCompletableFuture<Object> anyOf(Vertx vertx, CompletableFuture<?>... futures) {
CompletableFuture<Object> all = CompletableFuture.anyOf(futures);
return VertxCompletableFuture.from(vertx, all);
}
/**
* Returns a new CompletableFuture that is completed when any of the given CompletableFutures complete, with the
* same result. Otherwise, if it completed exceptionally, the returned CompletableFuture also does so, with a
* CompletionException holding this exception as its cause. If no CompletableFutures are provided, returns an
* incomplete CompletableFuture.
* <p>
* Unlike the original {@link CompletableFuture#allOf(CompletableFuture[])} this method invokes the dependent
* stages into the Vert.x context.
*
* @param context the context
* @param futures the CompletableFutures
* @return a new CompletableFuture that is completed with the result or exception of any of the given
* CompletableFutures when one completes
* @throws NullPointerException if the array or any of its elements are {@code null}
*/
public static VertxCompletableFuture<Object> anyOf(Context context, CompletableFuture<?>... futures) {
CompletableFuture<Object> all = CompletableFuture.anyOf(futures);
return VertxCompletableFuture.from(context, all);
}
/**
* Returns a new CompletableFuture that is completed when any of the given CompletableFutures complete, with the
* same result. Otherwise, if it completed exceptionally, the returned CompletableFuture also does so, with a
* CompletionException holding this exception as its cause. If no CompletableFutures are provided, returns an
* incomplete CompletableFuture.
* <p>
* Unlike the original {@link CompletableFuture#allOf(CompletableFuture[])} this method invokes the dependent
* stages into the Vert.x context.
*
* @param vertx the Vert.x instance to retrieve the context
* @param futures the CompletableFutures
* @return a new CompletableFuture that is completed with the result or exception of any of the given
* CompletableFutures when one completes
* @throws NullPointerException if the array or any of its elements are {@code null}
*/
public static VertxCompletableFuture<Object> anyOf(Vertx vertx, CompletableFuture<?>... futures) {
CompletableFuture<Object> all = CompletableFuture.anyOf(futures);
return VertxCompletableFuture.from(vertx, all);
}
/**
* Returns a new CompletableFuture that is completed when any of the given CompletableFutures complete, with the
* same result. Otherwise, if it completed exceptionally, the returned CompletableFuture also does so, with a
* CompletionException holding this exception as its cause. If no CompletableFutures are provided, returns an
* incomplete CompletableFuture.
* <p>
* Unlike the original {@link CompletableFuture#allOf(CompletableFuture[])} this method invokes the dependent
* stages into the Vert.x context.
*
* @param context the context
* @param futures the CompletableFutures
* @return a new CompletableFuture that is completed with the result or exception of any of the given
* CompletableFutures when one completes
* @throws NullPointerException if the array or any of its elements are {@code null}
*/
public static VertxCompletableFuture<Object> anyOf(Context context, CompletableFuture<?>... futures) {
CompletableFuture<Object> all = CompletableFuture.anyOf(futures);
return VertxCompletableFuture.from(context, all);
}
/**
* Returns a new CompletableFuture that is completed when any of the given CompletableFutures complete, with the
* same result. Otherwise, if it completed exceptionally, the returned CompletableFuture also does so, with a
* CompletionException holding this exception as its cause. If no CompletableFutures are provided, returns an
* incomplete CompletableFuture.
* <p>
* Unlike the original {@link CompletableFuture#allOf(CompletableFuture[])} this method invokes the dependent
* stages into the Vert.x context.
*
* @param vertx the Vert.x instance to retrieve the context
* @param futures the CompletableFutures
* @return a new CompletableFuture that is completed with the result or exception of any of the given
* CompletableFutures when one completes
* @throws NullPointerException if the array or any of its elements are {@code null}
*/
public static VertxCompletableFuture<Object> anyOf(Vertx vertx, CompletableFuture<?>... futures) {
CompletableFuture<Object> all = CompletableFuture.anyOf(futures);
return VertxCompletableFuture.from(vertx, all);
}
/**
* Returns a new CompletableFuture that is completed when any of the given CompletableFutures complete, with the
* same result. Otherwise, if it completed exceptionally, the returned CompletableFuture also does so, with a
* CompletionException holding this exception as its cause. If no CompletableFutures are provided, returns an
* incomplete CompletableFuture.
* <p>
* Unlike the original {@link CompletableFuture#allOf(CompletableFuture[])} this method invokes the dependent
* stages into the Vert.x context.
*
* @param context the context
* @param futures the CompletableFutures
* @return a new CompletableFuture that is completed with the result or exception of any of the given
* CompletableFutures when one completes
* @throws NullPointerException if the array or any of its elements are {@code null}
*/
public static VertxCompletableFuture<Object> anyOf(Context context, CompletableFuture<?>... futures) {
CompletableFuture<Object> all = CompletableFuture.anyOf(futures);
return VertxCompletableFuture.from(context, all);
}
/**
* Returns a new CompletableFuture that is completed when any of the given CompletableFutures complete, with the
* same result. Otherwise, if it completed exceptionally, the returned CompletableFuture also does so, with a
* CompletionException holding this exception as its cause. If no CompletableFutures are provided, returns an
* incomplete CompletableFuture.
* <p>
* Unlike the original {@link CompletableFuture#allOf(CompletableFuture[])} this method invokes the dependent
* stages into the Vert.x context.
*
* @param vertx the Vert.x instance to retrieve the context
* @param futures the CompletableFutures
* @return a new CompletableFuture that is completed with the result or exception of any of the given
* CompletableFutures when one completes
* @throws NullPointerException if the array or any of its elements are {@code null}
*/
public static VertxCompletableFuture<Object> anyOf(Vertx vertx, CompletableFuture<?>... futures) {
CompletableFuture<Object> all = CompletableFuture.anyOf(futures);
return VertxCompletableFuture.from(vertx, all);
}