本文整理匯總了Java中java.util.concurrent.CompletableFuture.whenComplete方法的典型用法代碼示例。如果您正苦於以下問題:Java CompletableFuture.whenComplete方法的具體用法?Java CompletableFuture.whenComplete怎麽用?Java CompletableFuture.whenComplete使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.concurrent.CompletableFuture
的用法示例。
在下文中一共展示了CompletableFuture.whenComplete方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: sort
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
public static void sort(int[] array, int from, int to) {
int size = to - from;
if (size < cutoff) Arrays.sort(array, from, to);
else {
CompletableFuture<int[]> parsort1 = null; // TODO implement me
CompletableFuture<int[]> parsort2 = null; // TODO implement me
CompletableFuture<int[]> parsort = parsort1.
thenCombine(parsort2, (xs1, xs2) -> {
int[] result = new int[xs1.length + xs2.length];
// TODO implement me
return result;
});
parsort.whenComplete((result, throwable) -> {}); // TODO implement me
parsort.join();
}
}
示例2: testPut
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void testPut() throws TimeoutException {
final String content = "test file content";
final String key = "submission";
final Waiter waiter = new Waiter();
when(environment.getProperty(eq(Constants.BUCKET_NAME_ENV_VARIABLE))).thenReturn(bucketName);
CompletableFuture<String> result = underTest.store(
key, new ByteArrayInputStream(content.getBytes()), content.getBytes().length);
result.whenComplete((outcome, ex) -> {
waiter.assertEquals(content, getObjectContent(key));
waiter.resume();
});
waiter.await(5000);
}
示例3: testFileUploadFailureException
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void testFileUploadFailureException() throws TimeoutException {
when(environment.getProperty(Constants.NO_AUDIT_ENV_VARIABLE)).thenReturn(null);
successfulEncodingPrep();
problematic();
final Waiter waiter = new Waiter();
CompletableFuture<Void> future = underTest.success(report);
future.whenComplete((nada, ex) -> {
waiter.assertNull(metadata.getQppLocator());
waiter.assertNull(metadata.getSubmissionLocator());
waiter.assertTrue(ex.getCause() instanceof UncheckedInterruptedException);
waiter.resume();
});
waiter.await(5000);
}
示例4: success
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
* Audit a successful conversion.
*
* @param conversionReport report of the conversion
* @return future
*/
@Override
public CompletableFuture<Void> success(Converter.ConversionReport conversionReport) {
if (noAudit()) {
return null;
}
API_LOG.info("Writing success audit information");
Metadata metadata = initMetadata(conversionReport, Outcome.SUCCESS);
Source qrdaSource = conversionReport.getQrdaSource();
Source qppSource = conversionReport.getQppSource();
CompletableFuture<Void> allWrites = CompletableFuture.allOf(
storeContent(qrdaSource).thenAccept(metadata::setSubmissionLocator),
storeContent(qppSource).thenAccept(metadata::setQppLocator));
return allWrites.whenComplete((nada, thrown) -> persist(metadata, thrown));
}
示例5: expectIntentionalFailureOf
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void expectIntentionalFailureOf(CompletableFuture<Optional<TestProfile>> profileFuture) {
profileFuture.whenComplete((p, t) -> {
if (p != null) {
executionContext.runOnContext(() -> {
throw new RuntimeException("profile should be null");
});
} else {
AsyncExceptionHandler.handleException(t, e -> {
// Note implication of use of completeExceptionally
if (e instanceof IntentionalException) {
executionContext.runOnContext(() -> {
throw (IntentionalException) e;
});
}
throw new RuntimeException(e);
});
}
});
}
示例6: failValidation
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
* Audit a failed submission validation.
*
* @param conversionReport report of the conversion
* @return future
*/
@Override
public CompletableFuture<Void> failValidation(Converter.ConversionReport conversionReport) {
if (noAudit()) {
return null;
}
API_LOG.info("Writing audit information for a validation failure scenario");
Source qrdaSource = conversionReport.getQrdaSource();
Source qppSource = conversionReport.getQppSource();
Source validationErrorSource = conversionReport.getValidationErrorsSource();
Source rawValidationErrorSource = conversionReport.getRawValidationErrorsOrEmptySource();
Metadata metadata = initMetadata(conversionReport, Outcome.VALIDATION_ERROR);
CompletableFuture<Void> allWrites = CompletableFuture.allOf(
storeContent(rawValidationErrorSource).thenAccept(metadata::setRawValidationErrorLocator),
storeContent(validationErrorSource).thenAccept(metadata::setValidationErrorLocator),
storeContent(qppSource).thenAccept(metadata::setQppLocator),
storeContent(qrdaSource).thenAccept(metadata::setSubmissionLocator));
return allWrites.whenComplete((nada, thrown) -> persist(metadata, thrown));
}
示例7: submit
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
* Submits a value-returning task for execution to this worker and returns the pending result of the job.
*
* @param <Result> the type of pending result
* @param job the job to submit
* @return the pending result of the job
* @see Future
* @see ExecutorService#submit(java.util.concurrent.Callable)
*/
public <Result extends Serializable> Future<Result> submit(final Job<Result> job){
final UUID job_id = UUID.randomUUID();
final FutureRemote<Result> future_remote = new FutureRemote<>(job_id, proxy);
network.notifyJobSubmission(future_remote);
final CompletableFuture<Void> job_submission = proxy.submit(job_id, job);
job_submission.whenComplete((result, error) -> {
if (job_submission.isCompletedExceptionally()) {
LOGGER.debug("failed to submit job {} to {} due to {}", job_id, proxy, error);
future_remote.completeExceptionally(error);
}
});
return future_remote;
}
示例8: scheduleTimeout
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private <T> void scheduleTimeout(CompletableFuture<T> result, long timeoutMillis) {
pendingFutures.add(result);
if (isServerStopping()) {
pendingFutures.remove(result);
return;
}
final ScheduledFuture<?> timeoutFuture;
if (timeoutMillis > 0) {
final EventLoop eventLoop = RequestContext.current().eventLoop();
timeoutFuture = eventLoop.schedule(() -> result.completeExceptionally(CANCELLATION_EXCEPTION),
timeoutMillis, TimeUnit.MILLISECONDS);
} else {
timeoutFuture = null;
}
result.whenComplete((revision, cause) -> {
if (timeoutFuture != null) {
timeoutFuture.cancel(true);
}
pendingFutures.remove(result);
});
}
示例9: requestReply
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void requestReply() {
try {
attempted.incrementAndGet();
CompletableFuture<Data> response =
communicationService.<Data, Data>sendAndReceive(
data,
TEST_REQUEST_REPLY_TOPIC,
encoder,
decoder,
randomPeer());
response.whenComplete((result, error) -> {
if (Objects.equals(data, result)) {
completed.incrementAndGet();
}
messageSendingExecutor.submit(this::requestReply);
});
} catch (Exception e) {
log.info("requestReply()", e);
}
}
示例10: testSendAsync
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void testSendAsync() {
CountDownLatch latch1 = new CountDownLatch(1);
CompletableFuture<Void> response = netty1.sendAsync(ep2, "test-subject", "hello world".getBytes());
response.whenComplete((r, e) -> {
assertNull(e);
latch1.countDown();
});
Uninterruptibles.awaitUninterruptibly(latch1);
CountDownLatch latch2 = new CountDownLatch(1);
response = netty1.sendAsync(invalidEndPoint, "test-subject", "hello world".getBytes());
response.whenComplete((r, e) -> {
assertNotNull(e);
latch2.countDown();
});
Uninterruptibles.awaitUninterruptibly(latch2);
}
示例11: handleActions
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void handleActions(
Iterator<Action> nextActions,
ChannelHandlerContext ctx,
Frame frame,
CompletableFuture<Void> doneFuture,
QueryLog queryLog) {
// If there are no more actions, complete the done future and return.
if (!nextActions.hasNext()) {
doneFuture.complete(null);
notifyQueryListeners(queryLog, true);
return;
}
CompletableFuture<Void> future = new CompletableFuture<>();
Action action = nextActions.next();
ActionHandler handler = new ActionHandler(action, ctx, frame, future);
if (action.delayInMs() > 0) {
timer.newTimeout(handler, action.delayInMs(), TimeUnit.MILLISECONDS);
} else {
// process immediately when delay is 0.
handler.run(null);
}
// proceed to next action when complete
future.whenComplete(
(v, ex) -> {
if (ex != null) {
doneFuture.completeExceptionally(ex);
} else {
handleActions(nextActions, ctx, frame, doneFuture, queryLog);
}
});
}
示例12: applyAsyncExceptionHandlingTo
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void applyAsyncExceptionHandlingTo(CompletableFuture<Integer> future) {
future.whenComplete((i, t) -> {
if (i != null) {
throw new RuntimeException("Future was supposed to fail");
} else {
AsyncExceptionHandler.handleException(t, e -> executionContext.runOnContext(() -> {
if (e instanceof IntentionalException) {
throw ((IntentionalException) e);
} else {
throw new RuntimeException(e);
}
}));
}
});
}
示例13: testAsyncExceptionalCompletion
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test(timeout = 1000, expected = IntentionalException.class)
public void testAsyncExceptionalCompletion(final TestContext testContext) throws Throwable {
final Context context = rule.vertx().getOrCreateContext();
Async async = testContext.async();
final int input = 1;
final CompletableFuture<Integer> future = new CompletableFuture<>();
rule.vertx().setTimer(500, i -> {
future.completeExceptionally(new IntentionalException());
});
future.whenComplete((i, t) -> {
if (i != null) {
context.runOnContext(v -> {
throw new RuntimeException("Future should not have completed successfully");
});
} else {
context.runOnContext(v -> {
if (t instanceof IntentionalException) {
// Note that the cast is not actually redundant - this will log as it hits the default
// exception handler, but will be expected by the test
throw (IntentionalException) t;
}
throw new RuntimeException(t);
});
}
});
}
示例14: handleUserResponse
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void handleUserResponse(final CompletableFuture<Object> future) {
future.whenComplete((resp, exc) -> {
if (exc != null) {
LOG.error("Could not wake up user due to: {}", exc.getCause().getMessage());
} else {
LOG.info("User [{}] is waked up", ((UserActorWakeUpMessage.Request) resp).getUserId());
}
});
}
示例15: setMainResponse
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
synchronized void setMainResponse(CompletableFuture<HttpResponse<T>> r) {
r.whenComplete((HttpResponse<T> response, Throwable t) -> {
if (t != null)
mainResponse.completeExceptionally(t);
else
mainResponse.complete(response);
});
}