Java Code Examples for java.util.concurrent.CompletableFuture#thenAcceptAsync()

The following examples show how to use java.util.concurrent.CompletableFuture#thenAcceptAsync() . 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: OperatorCoordinatorCheckpoints.java    From flink with Apache License 2.0 6 votes vote down vote up
public static CompletableFuture<Void> triggerAndAcknowledgeAllCoordinatorCheckpoints(
		final Collection<OperatorCoordinatorCheckpointContext> coordinators,
		final PendingCheckpoint checkpoint,
		final Executor acknowledgeExecutor) throws Exception {

	final CompletableFuture<AllCoordinatorSnapshots> snapshots =
			triggerAllCoordinatorCheckpoints(coordinators, checkpoint.getCheckpointId());

	return snapshots
			.thenAcceptAsync(
					(allSnapshots) -> {
						try {
							acknowledgeAllCoordinators(checkpoint, allSnapshots.snapshots);
						}
						catch (Exception e) {
							throw new CompletionException(e);
						}
					},
					acknowledgeExecutor);
}
 
Example 2
Source File: Collect.java    From coroutines with Apache License 2.0 5 votes vote down vote up
/***************************************
 * {@inheritDoc}
 */
@Override
public void runAsync(CompletableFuture<I>			 fPreviousExecution,
					 CoroutineStep<Collection<O>, ?> rNextStep,
					 Continuation<?>				 rContinuation)
{
	fPreviousExecution.thenAcceptAsync(
		rInput -> collectAsync(rInput, rNextStep, rContinuation));
}
 
Example 3
Source File: TestcontainersR2DBCConnectionFactory.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Override
public Publisher<Void> close() {
    return s -> {
        CompletableFuture<R2DBCDatabaseContainer> futureRef;
        synchronized (this) {
            futureRef = this.future;
            this.future = null;
        }

        CancellableSubscription subscription = new CancellableSubscription();
        s.onSubscribe(subscription);

        if (futureRef == null) {
            if (!subscription.isCancelled()) {
                s.onComplete();
            }
        } else {
            futureRef.thenAcceptAsync(Startable::stop, EXECUTOR);

            EXECUTOR.execute(() -> {
                futureRef.cancel(true);
                if (!subscription.isCancelled()) {
                    s.onComplete();
                }
            });
        }
    };
}
 
Example 4
Source File: ThreadBridge.java    From ReactFX with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected Subscription observeInputs() {
    CompletableFuture<Subscription> subscription = new CompletableFuture<>();
    sourceThreadExecutor.execute(() -> {
        subscription.complete(
                input.subscribe(e -> {
                    targetThreadExecutor.execute(() -> emit(e));
                }));
    });
    return () -> {
        subscription.thenAcceptAsync(
                Subscription::unsubscribe,
                sourceThreadExecutor);
    };
}
 
Example 5
Source File: AsynchronousSocketStep.java    From coroutines with Apache License 2.0 5 votes vote down vote up
/***************************************
 * {@inheritDoc}
 */
@Override
public void runAsync(CompletableFuture<ByteBuffer> fPreviousExecution,
					 CoroutineStep<ByteBuffer, ?>  rNextStep,
					 Continuation<?>			   rContinuation)
{
	fPreviousExecution.thenAcceptAsync(
		b -> connectAsync(b, rContinuation.suspend(this, rNextStep)),
		rContinuation);
}
 
Example 6
Source File: Iteration.java    From coroutines with Apache License 2.0 5 votes vote down vote up
/***************************************
 * {@inheritDoc}
 */
@Override
public void runAsync(CompletableFuture<I> fPreviousExecution,
					 CoroutineStep<C, ?>  rNextStep,
					 Continuation<?>	  rContinuation)
{
	C aResults =
		fCollectionFactory != null ? fCollectionFactory.get() : null;

	fPreviousExecution.thenAcceptAsync(
		i -> iterateAsync(i.iterator(), aResults, rNextStep, rContinuation));
}
 
Example 7
Source File: Loop.java    From coroutines with Apache License 2.0 5 votes vote down vote up
/***************************************
 * {@inheritDoc}
 */
@Override
public void runAsync(CompletableFuture<T> fPreviousExecution,
					 CoroutineStep<T, ?>  rNextStep,
					 Continuation<?>	  rContinuation)
{
	fPreviousExecution.thenAcceptAsync(
		i -> loopAsync(i, rNextStep, rContinuation));
}
 
Example 8
Source File: Async.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void onRemoval(@Nullable K key,
    @Nullable CompletableFuture<V> future, RemovalCause cause) {
  if (future != null) {
    future.thenAcceptAsync(value -> delegate.onRemoval(key, value, cause), executor);
  }
}
 
Example 9
Source File: GremlinDriverIntegrateTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldProcessSessionRequestsInOrder() throws Exception {
    final Cluster cluster = TestClientFactory.open();
    final Client client = cluster.connect(name.getMethodName());

    final ResultSet rsFive = client.submit("Thread.sleep(5000);'five'");
    final ResultSet rsZero = client.submit("'zero'");

    final CompletableFuture<List<Result>> futureFive = rsFive.all();
    final CompletableFuture<List<Result>> futureZero = rsZero.all();

    final CountDownLatch latch = new CountDownLatch(2);
    final List<String> order = new ArrayList<>();
    final ExecutorService executor = Executors.newSingleThreadExecutor();

    futureFive.thenAcceptAsync(r -> {
        order.add(r.get(0).getString());
        latch.countDown();
    }, executor);

    futureZero.thenAcceptAsync(r -> {
        order.add(r.get(0).getString());
        latch.countDown();
    }, executor);

    // wait for both results
    latch.await(30000, TimeUnit.MILLISECONDS);

    // should be two results
    assertEquals(2, order.size());

    // ensure that "five" is first then "zero"
    assertThat(order, contains("five", "zero"));
}
 
Example 10
Source File: ButterflyFacadeImpl.java    From butterfly with MIT License 5 votes vote down vote up
private CompletableFuture<TransformationResult> transform(TransformationRequest transformationRequest) {
    Configuration configuration = transformationRequest.getConfiguration();
    if (logger.isDebugEnabled()) {
        logger.debug("Transformation request configuration: {}", configuration);
    }

    CompletableFuture<TransformationResult> transformationResult = transformationEngine.perform(transformationRequest);

    if(!configuration.isModifyOriginalFolder() && configuration.isZipOutput()){
        transformationResult.thenAcceptAsync(compressionHandler::compress);
    }

    return transformationResult;
}
 
Example 11
Source File: RetryingRegistration.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * This method performs a registration attempt and triggers either a success notification or a retry,
 * depending on the result.
 */
@SuppressWarnings("unchecked")
private void register(final G gateway, final int attempt, final long timeoutMillis) {
	// eager check for canceling to avoid some unnecessary work
	if (canceled) {
		return;
	}

	try {
		log.info("Registration at {} attempt {} (timeout={}ms)", targetName, attempt, timeoutMillis);
		CompletableFuture<RegistrationResponse> registrationFuture = invokeRegistration(gateway, fencingToken, timeoutMillis);

		// if the registration was successful, let the TaskExecutor know
		CompletableFuture<Void> registrationAcceptFuture = registrationFuture.thenAcceptAsync(
			(RegistrationResponse result) -> {
				if (!isCanceled()) {
					if (result instanceof RegistrationResponse.Success) {
						// registration successful!
						S success = (S) result;
						completionFuture.complete(Tuple2.of(gateway, success));
					}
					else {
						// registration refused or unknown
						if (result instanceof RegistrationResponse.Decline) {
							RegistrationResponse.Decline decline = (RegistrationResponse.Decline) result;
							log.info("Registration at {} was declined: {}", targetName, decline.getReason());
						} else {
							log.error("Received unknown response to registration attempt: {}", result);
						}

						log.info("Pausing and re-attempting registration in {} ms", retryingRegistrationConfiguration.getRefusedDelayMillis());
						registerLater(gateway, 1, retryingRegistrationConfiguration.getInitialRegistrationTimeoutMillis(), retryingRegistrationConfiguration.getRefusedDelayMillis());
					}
				}
			},
			rpcService.getExecutor());

		// upon failure, retry
		registrationAcceptFuture.whenCompleteAsync(
			(Void v, Throwable failure) -> {
				if (failure != null && !isCanceled()) {
					if (ExceptionUtils.stripCompletionException(failure) instanceof TimeoutException) {
						// we simply have not received a response in time. maybe the timeout was
						// very low (initial fast registration attempts), maybe the target endpoint is
						// currently down.
						if (log.isDebugEnabled()) {
							log.debug("Registration at {} ({}) attempt {} timed out after {} ms",
								targetName, targetAddress, attempt, timeoutMillis);
						}

						long newTimeoutMillis = Math.min(2 * timeoutMillis, retryingRegistrationConfiguration.getMaxRegistrationTimeoutMillis());
						register(gateway, attempt + 1, newTimeoutMillis);
					}
					else {
						// a serious failure occurred. we still should not give up, but keep trying
						log.error("Registration at {} failed due to an error", targetName, failure);
						log.info("Pausing and re-attempting registration in {} ms", retryingRegistrationConfiguration.getErrorDelayMillis());

						registerLater(gateway, 1, retryingRegistrationConfiguration.getInitialRegistrationTimeoutMillis(), retryingRegistrationConfiguration.getErrorDelayMillis());
					}
				}
			},
			rpcService.getExecutor());
	}
	catch (Throwable t) {
		completionFuture.completeExceptionally(t);
		cancel();
	}
}
 
Example 12
Source File: RetryingRegistration.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * This method resolves the target address to a callable gateway and starts the
 * registration after that.
 */
@SuppressWarnings("unchecked")
public void startRegistration() {
	if (canceled) {
		// we already got canceled
		return;
	}

	try {
		// trigger resolution of the target address to a callable gateway
		final CompletableFuture<G> rpcGatewayFuture;

		if (FencedRpcGateway.class.isAssignableFrom(targetType)) {
			rpcGatewayFuture = (CompletableFuture<G>) rpcService.connect(
				targetAddress,
				fencingToken,
				targetType.asSubclass(FencedRpcGateway.class));
		} else {
			rpcGatewayFuture = rpcService.connect(targetAddress, targetType);
		}

		// upon success, start the registration attempts
		CompletableFuture<Void> rpcGatewayAcceptFuture = rpcGatewayFuture.thenAcceptAsync(
			(G rpcGateway) -> {
				log.info("Resolved {} address, beginning registration", targetName);
				register(rpcGateway, 1, retryingRegistrationConfiguration.getInitialRegistrationTimeoutMillis());
			},
			rpcService.getExecutor());

		// upon failure, retry, unless this is cancelled
		rpcGatewayAcceptFuture.whenCompleteAsync(
			(Void v, Throwable failure) -> {
				if (failure != null && !canceled) {
					final Throwable strippedFailure = ExceptionUtils.stripCompletionException(failure);
					if (log.isDebugEnabled()) {
						log.debug(
							"Could not resolve {} address {}, retrying in {} ms.",
							targetName,
							targetAddress,
							retryingRegistrationConfiguration.getErrorDelayMillis(),
							strippedFailure);
					} else {
						log.info(
							"Could not resolve {} address {}, retrying in {} ms: {}",
							targetName,
							targetAddress,
							retryingRegistrationConfiguration.getErrorDelayMillis(),
							strippedFailure.getMessage());
					}

					startRegistrationLater(retryingRegistrationConfiguration.getErrorDelayMillis());
				}
			},
			rpcService.getExecutor());
	}
	catch (Throwable t) {
		completionFuture.completeExceptionally(t);
		cancel();
	}
}
 
Example 13
Source File: RetryingRegistration.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * This method resolves the target address to a callable gateway and starts the
 * registration after that.
 */
@SuppressWarnings("unchecked")
public void startRegistration() {
	if (canceled) {
		// we already got canceled
		return;
	}

	try {
		// trigger resolution of the target address to a callable gateway
		final CompletableFuture<G> rpcGatewayFuture;

		if (FencedRpcGateway.class.isAssignableFrom(targetType)) {
			rpcGatewayFuture = (CompletableFuture<G>) rpcService.connect(
				targetAddress,
				fencingToken,
				targetType.asSubclass(FencedRpcGateway.class));
		} else {
			rpcGatewayFuture = rpcService.connect(targetAddress, targetType);
		}

		// upon success, start the registration attempts
		CompletableFuture<Void> rpcGatewayAcceptFuture = rpcGatewayFuture.thenAcceptAsync(
			(G rpcGateway) -> {
				log.info("Resolved {} address, beginning registration", targetName);
				register(rpcGateway, 1, retryingRegistrationConfiguration.getInitialRegistrationTimeoutMillis());
			},
			rpcService.getExecutor());

		// upon failure, retry, unless this is cancelled
		rpcGatewayAcceptFuture.whenCompleteAsync(
			(Void v, Throwable failure) -> {
				if (failure != null && !canceled) {
					final Throwable strippedFailure = ExceptionUtils.stripCompletionException(failure);
					if (log.isDebugEnabled()) {
						log.debug(
							"Could not resolve {} address {}, retrying in {} ms.",
							targetName,
							targetAddress,
							retryingRegistrationConfiguration.getErrorDelayMillis(),
							strippedFailure);
					} else {
						log.info(
							"Could not resolve {} address {}, retrying in {} ms: {}.",
							targetName,
							targetAddress,
							retryingRegistrationConfiguration.getErrorDelayMillis(),
							strippedFailure.getMessage());
					}

					startRegistrationLater(retryingRegistrationConfiguration.getErrorDelayMillis());
				}
			},
			rpcService.getExecutor());
	}
	catch (Throwable t) {
		completionFuture.completeExceptionally(t);
		cancel();
	}
}
 
Example 14
Source File: PluginsReloadConfiguration.java    From besu with Apache License 2.0 4 votes vote down vote up
private void reloadPluginConfig(final BesuPlugin plugin) {
  final String name = plugin.getName().orElseThrow();
  LOG.info("Reloading plugin configuration: {}.", name);
  final CompletableFuture<Void> future = plugin.reloadConfiguration();
  future.thenAcceptAsync(aVoid -> LOG.info("Plugin {} has been reloaded.", name));
}
 
Example 15
Source File: CompletableFutureTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public <T> CompletableFuture<Void> thenAccept
    (CompletableFuture<T> f, Consumer<? super T> a) {
    return f.thenAcceptAsync(a, new ThreadExecutor());
}
 
Example 16
Source File: CompletableFutureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public <T> CompletableFuture<Void> thenAccept
    (CompletableFuture<T> f, Consumer<? super T> a) {
    return f.thenAcceptAsync(a, new ThreadExecutor());
}
 
Example 17
Source File: CompletableFutureTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public <T> CompletableFuture<Void> thenAccept
    (CompletableFuture<T> f, Consumer<? super T> a) {
    return f.thenAcceptAsync(a);
}
 
Example 18
Source File: RetryingRegistration.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * This method performs a registration attempt and triggers either a success notification or a retry,
 * depending on the result.
 */
@SuppressWarnings("unchecked")
private void register(final G gateway, final int attempt, final long timeoutMillis) {
	// eager check for canceling to avoid some unnecessary work
	if (canceled) {
		return;
	}

	try {
		log.debug("Registration at {} attempt {} (timeout={}ms)", targetName, attempt, timeoutMillis);
		CompletableFuture<RegistrationResponse> registrationFuture = invokeRegistration(gateway, fencingToken, timeoutMillis);

		// if the registration was successful, let the TaskExecutor know
		CompletableFuture<Void> registrationAcceptFuture = registrationFuture.thenAcceptAsync(
			(RegistrationResponse result) -> {
				if (!isCanceled()) {
					if (result instanceof RegistrationResponse.Success) {
						// registration successful!
						S success = (S) result;
						completionFuture.complete(Tuple2.of(gateway, success));
					}
					else {
						// registration refused or unknown
						if (result instanceof RegistrationResponse.Decline) {
							RegistrationResponse.Decline decline = (RegistrationResponse.Decline) result;
							log.info("Registration at {} was declined: {}", targetName, decline.getReason());
						} else {
							log.error("Received unknown response to registration attempt: {}", result);
						}

						log.info("Pausing and re-attempting registration in {} ms", retryingRegistrationConfiguration.getRefusedDelayMillis());
						registerLater(gateway, 1, retryingRegistrationConfiguration.getInitialRegistrationTimeoutMillis(), retryingRegistrationConfiguration.getRefusedDelayMillis());
					}
				}
			},
			rpcService.getExecutor());

		// upon failure, retry
		registrationAcceptFuture.whenCompleteAsync(
			(Void v, Throwable failure) -> {
				if (failure != null && !isCanceled()) {
					if (ExceptionUtils.stripCompletionException(failure) instanceof TimeoutException) {
						// we simply have not received a response in time. maybe the timeout was
						// very low (initial fast registration attempts), maybe the target endpoint is
						// currently down.
						if (log.isDebugEnabled()) {
							log.debug("Registration at {} ({}) attempt {} timed out after {} ms",
								targetName, targetAddress, attempt, timeoutMillis);
						}

						long newTimeoutMillis = Math.min(2 * timeoutMillis, retryingRegistrationConfiguration.getMaxRegistrationTimeoutMillis());
						register(gateway, attempt + 1, newTimeoutMillis);
					}
					else {
						// a serious failure occurred. we still should not give up, but keep trying
						log.error("Registration at {} failed due to an error", targetName, failure);
						log.info("Pausing and re-attempting registration in {} ms", retryingRegistrationConfiguration.getErrorDelayMillis());

						registerLater(gateway, 1, retryingRegistrationConfiguration.getInitialRegistrationTimeoutMillis(), retryingRegistrationConfiguration.getErrorDelayMillis());
					}
				}
			},
			rpcService.getExecutor());
	}
	catch (Throwable t) {
		completionFuture.completeExceptionally(t);
		cancel();
	}
}
 
Example 19
Source File: FutureUtils.java    From flink with Apache License 2.0 3 votes vote down vote up
/**
 * This function takes a {@link CompletableFuture} and a consumer to accept the result of this future. If the input
 * future is already done, this function returns {@link CompletableFuture#thenAccept(Consumer)}. Otherwise, the
 * return value is {@link CompletableFuture#thenAcceptAsync(Consumer, Executor)} with the given executor.
 *
 * @param completableFuture the completable future for which we want to call #thenAccept.
 * @param executor the executor to run the thenAccept function if the future is not yet done.
 * @param consumer the consumer function to call when the future is completed.
 * @param <IN> type of the input future.
 * @return the new completion stage.
 */
public static <IN> CompletableFuture<Void> thenAcceptAsyncIfNotDone(
	CompletableFuture<IN> completableFuture,
	Executor executor,
	Consumer<? super IN> consumer) {
	return completableFuture.isDone() ?
		completableFuture.thenAccept(consumer) :
		completableFuture.thenAcceptAsync(consumer, executor);
}
 
Example 20
Source File: FutureUtils.java    From flink with Apache License 2.0 3 votes vote down vote up
/**
 * This function takes a {@link CompletableFuture} and a consumer to accept the result of this future. If the input
 * future is already done, this function returns {@link CompletableFuture#thenAccept(Consumer)}. Otherwise, the
 * return value is {@link CompletableFuture#thenAcceptAsync(Consumer, Executor)} with the given executor.
 *
 * @param completableFuture the completable future for which we want to call #thenAccept.
 * @param executor the executor to run the thenAccept function if the future is not yet done.
 * @param consumer the consumer function to call when the future is completed.
 * @param <IN> type of the input future.
 * @return the new completion stage.
 */
public static <IN> CompletableFuture<Void> thenAcceptAsyncIfNotDone(
	CompletableFuture<IN> completableFuture,
	Executor executor,
	Consumer<? super IN> consumer) {
	return completableFuture.isDone() ?
		completableFuture.thenAccept(consumer) :
		completableFuture.thenAcceptAsync(consumer, executor);
}