public static <T> void copyResults(CompletableFuture<T> source, CompletableFuture<T> target) { source.whenComplete((o, throwable) -> { if (throwable != null) { target.completeExceptionally(throwable); return; } target.complete(o); }); }
@Override public void onResponse(Call<R> call, Response<R> response) { if (response.isSuccessful()) { future.complete(response.body()); } else { future.completeExceptionally(new HttpException(response)); } }
private <T> CompletableFuture<T> wrap(CompletableFuture<T> future) { CompletableFuture<T> asyncFuture = new CompletableFuture<>(); future.whenCompleteAsync((r, e) -> { if (e != null) { asyncFuture.completeExceptionally(e); } else { asyncFuture.complete(r); } }, pool); return asyncFuture; }
@PostConstruct void init() throws ExecutionException, InterruptedException { VertxOptions options = new VertxOptions() .setClusterManager(new HazelcastClusterManager(hazelcastInstance)); CompletableFuture<Vertx> future = new CompletableFuture<>(); Vertx.clusteredVertx(options, ar -> { if (ar.succeeded()) { future.complete(ar.result()); } else { future.completeExceptionally(ar.cause()); } }); vertx = future.get(); }
@Override public CompletableFuture<Void> abort() { TransactionId transactionId = this.transactionId; if (transactionId == null) { return CompletableFuture.completedFuture(null); } CompletableFuture<Void> future = new CompletableFuture<>(); transactionService.complete(transactionId).whenComplete((completeResult, completeError) -> Futures.allOf(participants.stream().map(TransactionParticipant::close).collect(Collectors.toList())) .whenComplete((closeResult, closeError) -> { if (completeError != null) { future.completeExceptionally(completeError); } else if (closeError != null) { future.completeExceptionally(closeError); } else { future.complete(null); } })); return future; }
private void loadContent() throws ExecutionException { if (future.isDone()) { try { future.get(); } catch (InterruptedException e) { throw new RuntimeException("unreachable", e); } } // No more retry CURRENT_RETRY_UPDATER.set(this, maxRetry); if (CONTENT_PROCESSED_FIELD.getAndSet(this, 1) == 0) { try { future.complete(asyncHandler.onCompleted()); } catch (Throwable ex) { if (ON_THROWABLE_CALLED_FIELD.getAndSet(this, 1) == 0) { try { try { asyncHandler.onThrowable(ex); } catch (Throwable t) { LOGGER.debug("asyncHandler.onThrowable", t); } } finally { cancelTimeouts(); } } future.completeExceptionally(ex); } } future.getNow(null); }
@Override public CompletableFuture<Void> release(T object) { if (!all.contains(object)) { return Futures.failed(NOT_PART_OF_POOL); } if (idleCount.get() >= getMaxIdle()) { return destroy0(object); } if (isTestOnRelease()) { CompletableFuture<Boolean> valid = factory.validate(object); CompletableFuture<Void> res = new CompletableFuture<>(); valid.whenComplete((state1, throwable) -> { if (state1 != null && state1) { return0(object).whenComplete((x, y) -> res.complete(null)); } else { destroy0(object).whenComplete((x, y) -> res.complete(null)); } }); return res; } return return0(object); }
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NP_NONNULL_PARAM_VIOLATION", justification="it is valid to pass NULL to CompletableFuture#completedFuture") private CompletableFuture<Void> closeConn() { CompletableFuture<AsyncConnection> f = future.get(); if (f == null) { return CompletableFuture.completedFuture(null); } CompletableFuture<Void> closeFuture = new CompletableFuture<>(); f.whenComplete((conn, error) -> { if (error == null) { IOUtils.closeQuietly(conn); } closeFuture.complete(null); }); return closeFuture; }
private void executeActionAsync( final CompletableFuture<KvStateResponse> result, final KvStateRequest request, final boolean update) { if (!result.isDone()) { final CompletableFuture<KvStateResponse> operationFuture = getState(request, update); operationFuture.whenCompleteAsync( (t, throwable) -> { if (throwable != null) { if ( throwable.getCause() instanceof UnknownKvStateIdException || throwable.getCause() instanceof UnknownKvStateKeyGroupLocationException || throwable.getCause() instanceof ConnectException ) { // These failures are likely to be caused by out-of-sync // KvStateLocation. Therefore we retry this query and // force look up the location. LOG.debug("Retrying after failing to retrieve state due to: {}.", throwable.getCause().getMessage()); executeActionAsync(result, request, true); } else { result.completeExceptionally(throwable); } } else { result.complete(t); } }, queryExecutor); result.whenComplete( (t, throwable) -> operationFuture.cancel(false)); } }
/** * Tests disposal with a JAR file. */ @Test public void testDisposeWithJar() throws Exception { replaceStdOutAndStdErr(); final CompletableFuture<String> disposeSavepointFuture = new CompletableFuture<>(); final DisposeSavepointClusterClient clusterClient = new DisposeSavepointClusterClient( (String savepointPath) -> { disposeSavepointFuture.complete(savepointPath); return CompletableFuture.completedFuture(Acknowledge.get()); }, getConfiguration()); try { CliFrontend frontend = new MockedCliFrontend(clusterClient); // Fake JAR file File f = tmp.newFile(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f)); out.close(); final String disposePath = "any-path"; String[] parameters = { "-d", disposePath, "-j", f.getAbsolutePath() }; frontend.savepoint(parameters); final String actualSavepointPath = disposeSavepointFuture.get(); assertEquals(disposePath, actualSavepointPath); } finally { clusterClient.shutdown(); restoreStdOutAndStdErr(); } }
public static CompletableFuture<Void> waitForAll(List<CompletableFuture<Void>> futures) { final CompletableFuture<Void> compositeFuture = new CompletableFuture<>(); final AtomicInteger count = new AtomicInteger(futures.size()); for (CompletableFuture<Void> future : futures) { future.whenComplete((r, ex) -> { if (ex != null) { compositeFuture.completeExceptionally(ex); } else if (count.decrementAndGet() == 0) { // All the pending futures did complete compositeFuture.complete(null); } }); } if (futures.isEmpty()) { compositeFuture.complete(null); } return compositeFuture; } }
@Override public void onResponse(Call<R> call, Response<R> response) { if (response.isSuccessful()) { future.complete(response.body()); } else { future.completeExceptionally(new HttpException(response)); } }
@Test(timeOut = 20000) public void createOptimisticBaseNotExist() throws Exception { CompletableFuture<Void> promise = new CompletableFuture<>(); MetaStoreImplZookeeper.asyncCreateFullPathOptimistic( zkc, "/foo", "bar/zar/gar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> { if (rc != KeeperException.Code.OK.intValue()) { promise.completeExceptionally(KeeperException.create(rc)); } else { promise.complete(null); } }); try { promise.get(); fail("should have failed"); } catch (ExecutionException ee) { assertEquals(ee.getCause().getClass(), KeeperException.NoNodeException.class); } }
public boolean deleteDatabaseConnection( String database ) { CompletableFuture<Boolean> future = new CompletableFuture<>(); spoonSupplier.get().getShell().getDisplay().asyncExec( () -> { removeDatabase( database ); future.complete( true ); } ); try { return future.get(); } catch ( Exception e ) { return false; } }
@Override public CompletableFuture<Void> closeAsync() { if (getState() == State.Closing || getState() == State.Closed) { unAckedMessageTracker.close(); return CompletableFuture.completedFuture(null); } setState(State.Closing); CompletableFuture<Void> closeFuture = new CompletableFuture<>(); List<CompletableFuture<Void>> futureList = consumers.values().stream() .map(c -> c.closeAsync()).collect(Collectors.toList()); FutureUtil.waitForAll(futureList) .whenComplete((r, ex) -> { if (ex == null) { setState(State.Closed); unAckedMessageTracker.close(); closeFuture.complete(null); log.info("[{}] [{}] Closed Topics Consumer", topic, subscription); client.cleanupConsumer(this); // fail all pending-receive futures to notify application failPendingReceive(); } else { setState(State.Failed); closeFuture.completeExceptionally(ex); log.error("[{}] [{}] Could not close Topics Consumer", topic, subscription, ex.getCause()); } }); return closeFuture; }
future.whenComplete((v, t) -> { RpcResult rpcResult; if (t != null) { rFuture.complete(rpcResult); });
/** * Closes the primary-backup partition. */ public CompletableFuture<Void> close() { if (client == null) { return CompletableFuture.completedFuture(null); } CompletableFuture<Void> future = new CompletableFuture<>(); client.stop().whenComplete((clientResult, clientError) -> { if (server != null) { server.stop().whenComplete((serverResult, serverError) -> { future.complete(null); }); } else { future.complete(null); } }); return future; }
(failForUnknownKeyOrNamespace && throwable.getCause() instanceof UnknownKeyOrNamespaceException) ) { resultFuture.completeExceptionally(throwable.getCause()); } else if (deadline.hasTimeLeft()) { getKvStateIgnoringCertainExceptions( resultFuture.complete(result); resultFuture.whenComplete((result, throwable) -> expected.cancel(false));
private <T> CompletableFuture<T> wrap(CompletableFuture<T> future) { CompletableFuture<T> asyncFuture = new CompletableFuture<>(); future.whenCompleteAsync((r, e) -> { if (e != null) { asyncFuture.completeExceptionally(e); } else { asyncFuture.complete(r); } }, pool); return asyncFuture; }