Java Code Examples for java.util.concurrent.CompletionStage#whenComplete()
The following examples show how to use
java.util.concurrent.CompletionStage#whenComplete() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CompletionStageUtils.java From resilience4j with Apache License 2.0 | 6 votes |
/** * Returns a CompletionStage that is recovered from a specific exception. * * @param completionStage the completionStage which should be recovered from a certain exception * @param exceptionType the specific exception type that should be recovered * @param exceptionHandler the function applied after callable has failed * @return a CompletionStage that is recovered from a specific exception. */ public static <X extends Throwable, T> CompletionStage<T> recover(CompletionStage<T> completionStage, Class<X> exceptionType, Function<Throwable, T> exceptionHandler){ CompletableFuture<T> promise = new CompletableFuture<>(); completionStage.whenComplete((result, throwable) -> { if (throwable != null){ if (throwable instanceof CompletionException || throwable instanceof ExecutionException) { tryRecover(exceptionType, exceptionHandler, promise, throwable.getCause()); }else{ tryRecover(exceptionType, exceptionHandler, promise, throwable); } } else { promise.complete(result); } }); return promise; }
Example 2
Source File: SingleToCompletionStageTest.java From servicetalk with Apache License 2.0 | 6 votes |
@Test public void cancellationOnDependentCancelsSource() throws InterruptedException { CountDownLatch cancelLatch = new CountDownLatch(1); CompletionStage<String> stage = source.afterCancel(cancelLatch::countDown).toCompletionStage(); AtomicReference<Throwable> causeRef = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); stage = stage.whenComplete((s, t) -> causeRef.compareAndSet(null, t)) .whenComplete((s, t) -> causeRef.compareAndSet(null, t)); stage.whenComplete((s, t) -> { causeRef.compareAndSet(null, t); latch.countDown(); }); stage.toCompletableFuture().cancel(true); latch.await(); assertThat(causeRef.get(), is(instanceOf(CancellationException.class))); cancelLatch.await(); }
Example 3
Source File: AsyncMethodExecutor.java From tascalate-async-await with BSD 2-Clause "Simplified" License | 6 votes |
protected <R, E extends Throwable> void setupContinuation(Continuation continuation) { @SuppressWarnings("unchecked") SuspendParams<R> suspendParams = (SuspendParams<R>)continuation.value(); CompletionStage<R> future = suspendParams.future; AbstractAsyncMethod suspendedMethod = suspendParams.suspendedMethod; ContinuationResumer<? super R, Throwable> originalResumer = new ContinuationResumer<>(continuation); Runnable wrappedResumer = suspendedMethod.createResumeHandler(originalResumer); // Setup future and give it a chance to continue the Continuation try { future.whenComplete((r, e) -> { originalResumer.setup(r, e); wrappedResumer.run(); }); } catch (Throwable error) { resume(continuation, FutureResult.failure(error)); } }
Example 4
Source File: GrpcStateService.java From flink with Apache License 2.0 | 6 votes |
@Override public void onNext(StateRequest request) { StateRequestHandler handler = requestHandlers.getOrDefault(request.getInstructionId(), this::handlerNotFound); try { CompletionStage<StateResponse.Builder> result = handler.handle(request); result.whenComplete( (StateResponse.Builder responseBuilder, Throwable t) -> // note that this is threadsafe if and only if outboundObserver is threadsafe. outboundObserver.onNext( t == null ? responseBuilder.setId(request.getId()).build() : createErrorResponse(request.getId(), t))); } catch (Exception e) { outboundObserver.onNext(createErrorResponse(request.getId(), e)); } }
Example 5
Source File: AsyncAwaitNioFileChannelDemo.java From tascalate-async-await with BSD 2-Clause "Simplified" License | 6 votes |
public static void main(final String[] argv) throws Exception { final AsyncAwaitNioFileChannelDemo demo = new AsyncAwaitNioFileChannelDemo(); final CompletionStage<String> result = demo.processFile("./.project"); System.out.println("Returned to caller " + LocalTime.now()); final CompletionStage<?> waiter = result.whenComplete((r, e) -> { if ( e != null ) { System.out.println("Error " + LocalTime.now()); e.printStackTrace(System.out); } else { System.out.println("Result " + LocalTime.now()); System.out.println(r); } }); // Need to wait because NIO uses daemon threads that do not prevent program exit System.out.println("Start waiting for result to prevent program close..."); waiter.toCompletableFuture().join(); }
Example 6
Source File: SimpleCompletionStage.java From java-async-util with Apache License 2.0 | 6 votes |
@Override public <U> CompletionStage<U> applyToEitherAsync(final CompletionStage<? extends T> other, final Function<? super T, U> fn, final Executor executor) { Objects.requireNonNull(fn); final SimpleCompletionStage<T> scs = new SimpleCompletionStage<>(); runOrPush((res, t, exc) -> scs.completeEncoded(res)); other.whenComplete((t, exc) -> { if (exc == null) { scs.complete(t); } else { scs.completeExceptionally(exc); } }); return scs.thenApplyAsync(fn, executor); }
Example 7
Source File: HttpServer.java From netty-rest with Apache License 2.0 | 6 votes |
void handleAsyncJsonRequest(ObjectMapper mapper, RakamHttpRequest request, CompletionStage apply) { if (apply == null) { NullPointerException e = new NullPointerException(); uncaughtExceptionHandler.handle(request, e); LOGGER.error(e, "Error while processing request. The async method returned null."); return; } apply.whenComplete((BiConsumer<Object, Throwable>) (result, ex) -> { if (ex != null) { while (ex instanceof CompletionException) { ex = ex.getCause(); } uncaughtExceptionHandler.handle(request, ex); requestError(ex, request); } else { returnJsonResponse(mapper, request, OK, result); } }); }
Example 8
Source File: BaseReactiveTest.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 6 votes |
protected static void test(TestContext context, CompletionStage<?> cs) { // this will be added to TestContext in the next vert.x release Async async = context.async(); cs.whenComplete( (res, err) -> { if ( res instanceof Stage.Session ) { Stage.Session s = (Stage.Session) res; if ( s.isOpen() ) { s.close(); } } if ( err != null ) { context.fail( err ); } else { async.complete(); } } ); }
Example 9
Source File: CompletionStageWrapper.java From tascalate-concurrent with Apache License 2.0 | 6 votes |
protected CompletionStageWrapper(CompletionStage<T> delegate) { super(delegate); whenDone = new CountDownLatch(1); result = null; fault = null; delegate.whenComplete((r, e) -> { // It's a responsibility of delegate to call // this callback at most once -- any valid // implementation should not invoke callback // more than once, so result/fault will not // be overwritten result = r; fault = e; whenDone.countDown(); }); }
Example 10
Source File: CompletableFutureHelper.java From microprofile-fault-tolerance with Apache License 2.0 | 5 votes |
/** * Returns a future that is completed when the stage is completed and has the same value or exception * as the completed stage. It's supposed to be equivalent to calling * {@link CompletionStage#toCompletableFuture()} but works with any CompletionStage * and doesn't throw {@link java.lang.UnsupportedOperationException}. * * @param <U> The type of the future result * @param stage Stage to convert to a future * @return Future converted from stage */ public static <U> CompletableFuture<U> toCompletableFuture(CompletionStage<U> stage) { CompletableFuture<U> future = new CompletableFuture<>(); stage.whenComplete((v, e) -> { if (e != null) { future.completeExceptionally(e); } else { future.complete(v); } }); return future; }
Example 11
Source File: FromCompletionStageFactoryTest.java From smallrye-reactive-streams-operators with Apache License 2.0 | 5 votes |
@Test public void createFromFutureGoingToBeFailed() { CompletableFuture<String> cf = new CompletableFuture<>(); CompletionStage<Optional<String>> stage = ReactiveStreams.fromCompletionStage(cf).findFirst().run(); AtomicBoolean done = new AtomicBoolean(); stage.whenComplete((res, err) -> { assertThat(err).isNotNull().hasMessageContaining("Expected"); assertThat(res).isNull(); done.set(true); }); new Thread(() -> cf.completeExceptionally(new Exception("Expected"))).start(); await().untilAtomic(done, is(true)); }
Example 12
Source File: DittoService.java From ditto with Eclipse Public License 2.0 | 5 votes |
private void startAkkaManagement(final ActorSystem actorSystem) { logger.info("Starting AkkaManagement ..."); final AkkaManagement akkaManagement = AkkaManagement.get(actorSystem); final CompletionStage<Uri> startPromise = akkaManagement.start(); startPromise.whenComplete((uri, throwable) -> { if (null != throwable) { logger.error("Error during start of AkkaManagement: <{}>!", throwable.getMessage(), throwable); } else { logger.info("Started AkkaManagement on URI <{}>.", uri); } }); }
Example 13
Source File: SingleToCompletionStageTest.java From servicetalk with Apache License 2.0 | 5 votes |
@Test public void cancellationBeforeListen() throws InterruptedException { CompletionStage<String> stage = source.toCompletionStage(); AtomicReference<Throwable> causeRef = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); stage.toCompletableFuture().cancel(true); stage.whenComplete((s, t) -> { causeRef.set(t); latch.countDown(); }); assertTrue(latch.await(100, MILLISECONDS)); }
Example 14
Source File: ReactiveConnectionPoolTest.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 5 votes |
protected static void test(TestContext context, CompletionStage<?> cs) { // this will be added to TestContext in the next vert.x release Async async = context.async(); cs.whenComplete( (res, err) -> { if ( err != null ) { context.fail( err ); } else { async.complete(); } } ); }
Example 15
Source File: ApiServiceImpl.java From apicurio-registry with Apache License 2.0 | 5 votes |
public void apiSchemasPost(AsyncResponse response, NewSchema schema, boolean verify) throws ArtifactNotFoundException { String artifactId = schema.getName(); if (artifactId == null) { artifactId = idGenerator.generate(); } ContentHandle content = ContentHandle.create(schema.getDefinition()); if (verify) { rulesService.applyRules(artifactId, ArtifactType.AVRO, content, RuleApplicationType.CREATE); response.resume(Response.ok().entity(content).build()); } else { CompletionStage<ArtifactMetaDataDto> csArtifact = storage.createArtifact(artifactId, ArtifactType.AVRO, content); csArtifact.whenComplete((amdd, t) -> { if (t != null) { response.resume(t); } else { SchemaInfo info = new SchemaInfo(); info.setId(amdd.getId()); info.setEnabled(true); info.setVersions(getSchemaVersions(amdd.getId())); response.resume(Response.status(Response.Status.CREATED).entity(info).build()); } }); } }
Example 16
Source File: FromCompletionStageFactoryTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void createFromFutureGoingToBeFailed() { CompletableFuture<String> cf = new CompletableFuture<>(); CompletionStage<Optional<String>> stage = ReactiveStreams.fromCompletionStage(cf).findFirst().run(); AtomicBoolean done = new AtomicBoolean(); stage.whenComplete((res, err) -> { assertThat(err).isNotNull().hasMessageContaining("Expected"); assertThat(res).isNull(); done.set(true); }); new Thread(() -> cf.completeExceptionally(new Exception("Expected"))).start(); await().untilAtomic(done, is(true)); }
Example 17
Source File: FromCompletionStageFactoryTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void createFromFutureGoingToBeCompleted() { CompletableFuture<String> cf = new CompletableFuture<>(); CompletionStage<Optional<String>> stage = ReactiveStreams.fromCompletionStage(cf).findFirst().run(); AtomicBoolean done = new AtomicBoolean(); stage.whenComplete((res, err) -> { assertThat(err).isNull(); assertThat(res).contains("Hello"); done.set(true); }); new Thread(() -> cf.complete("Hello")).start(); await().untilAtomic(done, is(true)); }
Example 18
Source File: FromCompletionStageFactoryNullableTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void createFromFutureGoingToBeCompleted() { CompletableFuture<String> cf = new CompletableFuture<>(); CompletionStage<Optional<String>> stage = ReactiveStreams.fromCompletionStageNullable(cf).findFirst().run(); AtomicBoolean done = new AtomicBoolean(); stage.whenComplete((res, err) -> { assertThat(err).isNull(); assertThat(res).contains("Hello"); done.set(true); }); new Thread(() -> cf.complete("Hello")).start(); await().untilAtomic(done, is(true)); }
Example 19
Source File: FutureUtils.java From besu with Apache License 2.0 | 5 votes |
/** * Propagates the result of one {@link CompletionStage} to a different {@link CompletableFuture}. * * <p>When <code>from</code> completes successfully, <code>to</code> will be completed * successfully with the same value. When <code>from</code> completes exceptionally, <code>to * </code> will be completed exceptionally with the same exception. * * @param from the CompletionStage to take results and exceptions from * @param to the CompletableFuture to propagate results and exceptions to * @param <T> the type of the success value */ public static <T> void propagateResult( final CompletionStage<T> from, final CompletableFuture<T> to) { from.whenComplete( (value, error) -> { if (error != null) { to.completeExceptionally(error); } else { to.complete(value); } }); }
Example 20
Source File: LavalinkTrackLoader.java From MantaroBot with GNU General Public License v3.0 | 5 votes |
public static void load(AudioPlayerManager manager, Lavalink<?> lavalink, String query, AudioLoadResultHandler handler) { Iterator<LavalinkSocket> sockets = lavalink.getNodes().iterator(); if (!sockets.hasNext()) { manager.loadItem(query, handler); return; } CompletionStage<Runnable> last = tryLoad(manager, sockets.next().getRemoteUri(), query, handler); while (sockets.hasNext()) { URI uri = sockets.next().getRemoteUri(); //TODO: java 12 replace this with the line commented below var cf = new CompletableFuture<Runnable>(); last.thenApply(CompletableFuture::completedStage) .exceptionally(e -> tryLoad(manager, uri, query, handler)) .thenCompose(Function.identity()) .thenAccept(cf::complete) .exceptionally(e -> { cf.completeExceptionally(e); return null; }); last = cf; //last = last.exceptionallyCompose(e -> tryLoad(manager, uri, query, handler)); } last.whenComplete((ok, oof) -> { if (oof != null) { handler.loadFailed(new FriendlyException("Failed to load", FriendlyException.Severity.SUSPICIOUS, oof)); } else { ok.run(); } }); }