當前位置: 首頁>>代碼示例>>Java>>正文


Java CompletableFuture.handle方法代碼示例

本文整理匯總了Java中java.util.concurrent.CompletableFuture.handle方法的典型用法代碼示例。如果您正苦於以下問題:Java CompletableFuture.handle方法的具體用法?Java CompletableFuture.handle怎麽用?Java CompletableFuture.handle使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.concurrent.CompletableFuture的用法示例。


在下文中一共展示了CompletableFuture.handle方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: handleWatchRepositoryResult

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void handleWatchRepositoryResult(
        CompletableFuture<com.linecorp.centraldogma.common.Revision> future,
        AsyncMethodCallback resultHandler) {
    future.handle(voidFunction((res, cause) -> {
        if (cause == null) {
            final WatchRepositoryResult wrr = new WatchRepositoryResult();
            wrr.setRevision(convert(res));
            resultHandler.onComplete(wrr);
        } else if (cause instanceof CancellationException) {
            if (watchService.isServerStopping()) {
                resultHandler.onError(new CentralDogmaException(ErrorCode.SHUTTING_DOWN));
            } else {
                resultHandler.onComplete(CentralDogmaConstants.EMPTY_WATCH_REPOSITORY_RESULT);
            }
        } else {
            logAndInvokeOnError("watchRepository", resultHandler, cause);
        }
    }));
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:20,代碼來源:CentralDogmaServiceImpl.java

示例2: handleWatchFileResult

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void handleWatchFileResult(
        CompletableFuture<QueryResult<Object>> future, AsyncMethodCallback resultHandler) {
    future.handle(voidFunction((res, cause) -> {
        if (cause == null) {
            final WatchFileResult wfr = new WatchFileResult();
            wfr.setRevision(convert(res.revision()));
            wfr.setType(convert(res.type()));
            wfr.setContent(res.contentAsText());
            resultHandler.onComplete(wfr);
        } else if (cause instanceof CancellationException) {
            if (watchService.isServerStopping()) {
                resultHandler.onError(new CentralDogmaException(ErrorCode.SHUTTING_DOWN));
            } else {
                resultHandler.onComplete(CentralDogmaConstants.EMPTY_WATCH_FILE_RESULT);
            }
        } else {
            logAndInvokeOnError("watchFile", resultHandler, cause);
        }
    }));
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:21,代碼來源:CentralDogmaServiceImpl.java

示例3: triggerCheckpoint

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Override
public CompletableFuture<Checkpoint> triggerCheckpoint(
        long checkpointId, long checkpointTimestamp, Executor executor) throws Exception {

    final String checkpointName = createCheckpointName(checkpointId);

    // The method only offers an 'Executor', but we need a 'ScheduledExecutorService'
    // Because the hook currently offers no "shutdown()" method, there is no good place to
    // shut down a long lived ScheduledExecutorService, so we create one per request
    // (we should change that by adding a shutdown() method to these hooks)
    // ths shutdown 

    final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    final CompletableFuture<Checkpoint> checkpointResult =
            this.readerGroup.initiateCheckpoint(checkpointName, scheduledExecutorService);

    // Add a timeout to the future, to prevent long blocking calls
    scheduledExecutorService.schedule(() -> checkpointResult.cancel(false), triggerTimeout, TimeUnit.MILLISECONDS);

    // we make sure the executor is shut down after the future completes
    checkpointResult.handle((success, failure) -> scheduledExecutorService.shutdownNow());

    return checkpointResult;
}
 
開發者ID:pravega,項目名稱:flink-connectors,代碼行數:26,代碼來源:ReaderCheckpointHook.java

示例4: testNoLockHeldForCancellationTokenContinuation

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void testNoLockHeldForCancellationTokenContinuation() {
	CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
	CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync(cancellationTokenSource.getToken());
	CompletableFuture<Void> handled = pollFuture.handle((result, exception) -> {
		try {
			ForkJoinPool.commonPool().submit(ExecutionContext.wrap(() -> {
				// Add presumably requires a private lock internally.
				// Since we're calling it on a different thread than the
				// blocking cancellation continuation, this should deadlock
				// if and only if the queue is holding a lock while invoking
				// our cancellation continuation (which they shouldn't be doing).
				queue.add(new GenericParameterHelper(1));
			})).get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
			return null;
		} catch (InterruptedException | ExecutionException | TimeoutException ex) {
			throw new CompletionException(ex);
		}
	});

	cancellationTokenSource.cancel();

	handled.join();
	Assert.assertEquals(1, queue.size());
}
 
開發者ID:tunnelvisionlabs,項目名稱:java-threading,代碼行數:26,代碼來源:AsyncQueueTest.java

示例5: verifyDoesNotInlineContinuations

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
 * Verifies that continuations scheduled on a future will not be executed inline with the specified completing
 * action.
 *
 * @param antecedent The future to test.
 * @param completingAction The action that results in the synchronous completion of the future.
 */
protected static void verifyDoesNotInlineContinuations(@NotNull CompletableFuture<?> antecedent, @NotNull Runnable completingAction) {
	Requires.notNull(antecedent, "antecedent");
	Requires.notNull(completingAction, "completingAction");

	CompletableFuture<Void> completingActionFinished = new CompletableFuture<>();
	CompletableFuture<Void> continuation = antecedent.handle((result, exception) -> {
		try {
			return completingActionFinished.get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
		} catch (InterruptedException | ExecutionException | TimeoutException ex) {
			throw new CompletionException(ex);
		}
	});

	completingAction.run();
	completingActionFinished.complete(null);

	// Rethrow the exception if it turned out it deadlocked.
	continuation.join();
}
 
開發者ID:tunnelvisionlabs,項目名稱:java-threading,代碼行數:27,代碼來源:TestBase.java

示例6: verifyCanInlineContinuations

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
 * Verifies that continuations scheduled on a future can be executed inline with the specified completing action.
 *
 * @param antecedent The future to test.
 * @param completingAction The action that results in the synchronous completion of the future.
 */
protected static void verifyCanInlineContinuations(@NotNull CompletableFuture<?> antecedent, @NotNull Runnable completingAction) {
	Requires.notNull(antecedent, "antecedent");
	Requires.notNull(completingAction, "completingAction");

	Thread callingThread = Thread.currentThread();
	CompletableFuture<Void> continuation = antecedent.handle((result, exception) -> {
		Assert.assertSame(callingThread, Thread.currentThread());
		return null;
	});

	completingAction.run();
	Assert.assertTrue(continuation.isDone());

	// Rethrow any exceptions.
	continuation.join();
}
 
開發者ID:tunnelvisionlabs,項目名稱:java-threading,代碼行數:23,代碼來源:TestBase.java

示例7: assertSuccessfulEvaluation

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
protected <T> CompletableFuture<Void> assertSuccessfulEvaluation (final CompletableFuture<T> future,
                                                                  final Consumer<T> assertions,
                                                                  final Async async){
    return future.handle((v, t) -> {
        if (t != null) {
            executionContext.runOnContext(ExceptionSoftener.softenRunnable(() -> {
                if (t instanceof CompletionException) {throw t.getCause();
            }else {
                            throw t;
                        }
                    }));
        } else {
            executionContext.runOnContext(() -> {
                assertions.accept(v);
                async.complete();
            });
        }
        return null;
    });
}
 
開發者ID:millross,項目名稱:pac4j-async,代碼行數:21,代碼來源:VertxAsyncTestBase.java

示例8: testCompletionStage_handle_wraps

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test public void testCompletionStage_handle_wraps() throws Exception {
  CompletableFuture<String> future = new CompletableFuture<>();
  MyException exception = new MyException("test");
  future.completeExceptionally(exception);
  CompletionStage<String> stage = future.handle((v, e) -> {
    throw new CompletionException(e);
  });
  assertCauseOf(ExecutionException.class, stage).isSameAs(exception);
}
 
開發者ID:google,項目名稱:mug,代碼行數:10,代碼來源:MaybeTest.java

示例9: handle

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private static void handle(CompletableFuture<?> future, AsyncMethodCallback resultHandler) {
    future.handle((res, cause) -> {
        if (cause != null) {
            resultHandler.onError(convert(cause));
        } else {
            resultHandler.onComplete(res);
        }
        return null;
    });
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:11,代碼來源:CentralDogmaServiceImpl.java

示例10: should_Clear_values_from_cache_after_errors

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void should_Clear_values_from_cache_after_errors() {
    List<Collection<Integer>> loadCalls = new ArrayList<>();
    DataLoader<Integer, Integer> errorLoader = idLoaderBlowsUps(new DataLoaderOptions(), loadCalls);

    CompletableFuture<Integer> future1 = errorLoader.load(1);
    future1.handle((value, t) -> {
        if (t != null) {
            // Presumably determine if this error is transient, and only clear the cache in that case.
            errorLoader.clear(1);
        }
        return null;
    });
    errorLoader.dispatch();

    await().until(future1::isDone);
    assertThat(future1.isCompletedExceptionally(), is(true));
    assertThat(cause(future1), instanceOf(IllegalStateException.class));

    CompletableFuture<Integer> future2 = errorLoader.load(1);
    future2.handle((value, t) -> {
        if (t != null) {
            // Again, only do this if you can determine the error is transient.
            errorLoader.clear(1);
        }
        return null;
    });
    errorLoader.dispatch();

    await().until(future2::isDone);
    assertThat(future2.isCompletedExceptionally(), is(true));
    assertThat(cause(future2), instanceOf(IllegalStateException.class));
    assertThat(loadCalls, equalTo(asList(singletonList(1), singletonList(1))));
}
 
開發者ID:bbakerman,項目名稱:java-dataloader,代碼行數:35,代碼來源:DataLoaderTest.java

示例11: testNoLockHeldForCancellationContinuation

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void testNoLockHeldForCancellationContinuation() {
	CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync();
	CompletableFuture<Void> handled = pollFuture.handle((result, exception) -> {
		try {
			ForkJoinPool.commonPool().submit(ExecutionContext.wrap(() -> {
				// Add presumably requires a private lock internally.
				// Since we're calling it on a different thread than the
				// blocking cancellation continuation, this should deadlock
				// if and only if the queue is holding a lock while invoking
				// our cancellation continuation (which they shouldn't be doing).
				queue.add(new GenericParameterHelper(1));
			})).get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
			return null;
		} catch (InterruptedException | ExecutionException | TimeoutException ex) {
			throw new CompletionException(ex);
		}
	});

	pollFuture.cancel(true);

	handled.join();
	Assert.assertEquals(1, queue.size());
}
 
開發者ID:tunnelvisionlabs,項目名稱:java-threading,代碼行數:25,代碼來源:AsyncQueueTest.java

示例12: itExecutesReturnedExceptionalFuturesOnTheProvidedExecutor

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void itExecutesReturnedExceptionalFuturesOnTheProvidedExecutor() {
  ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("SmtpSessionTestExecutor").build());
  SmtpSession session = new SmtpSession(channel, responseHandler, CONFIG, executorService, SSL_ENGINE_SUPPLIER);

  CompletableFuture<SmtpClientResponse> future = session.send(SMTP_REQUEST);
  CompletableFuture<Boolean> assertionFuture = future.handle((r, e) -> {
    assertThat(Thread.currentThread().getName()).contains("SmtpSessionTestExecutor");
    return true;
  });

  responseFuture.completeExceptionally(new RuntimeException());
  assertionFuture.join();
}
 
開發者ID:HubSpot,項目名稱:NioSmtpClient,代碼行數:15,代碼來源:SmtpSessionTest.java

示例13: applyExceptionHandling

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Override
public CompletableFuture<T> applyExceptionHandling(CompletableFuture<T> future, AsyncWebContext webContext) {
    return future.handle(ExceptionSoftener.softenBiFunction((v, t) -> {
       if (v != null) {
           return v;
       } else {
           throw t;
       }
    }));
}
 
開發者ID:millross,項目名稱:pac4j-async,代碼行數:11,代碼來源:NoopAsyncExceptionHandler.java

示例14: applyExceptionHandling

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Override
public CompletableFuture<T> applyExceptionHandling(CompletableFuture<T> future, AsyncWebContext webContext) {
    return future.handle((v, t) -> {
        if (t != null) {
            webContext.getExecutionContext().runOnContext(ExceptionSoftener.softenRunnable(() -> {
                throw t;
            }));
            return null;
        } else {
            return v;
        }
    });
}
 
開發者ID:millross,項目名稱:pac4j-async,代碼行數:14,代碼來源:DefaultAsyncExceptionHandler.java

示例15: retrieveUserProfileFuture

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
 * Retrieve a user userprofile.
 *
 * @param credentials the credentials
 * @param context the web context
 * @return CompletableFuture wrapping the user profile
 * Note that unlike the sync version this won't throw HttpAction as that's a job for the underlying computation,
 * rather than the future wrapper
 */
protected CompletableFuture<Optional<U>> retrieveUserProfileFuture(final C credentials, final AsyncWebContext context) {
    final CompletableFuture<U> profileFuture = this.profileCreator.create(credentials, context);
    return profileFuture.handle((profile, failure) -> {
        if (failure == null) {
            logger.debug("profile: {}", profile);
        }
        return Optional.ofNullable(profile);
    });
}
 
開發者ID:millross,項目名稱:pac4j-async,代碼行數:19,代碼來源:AsyncBaseClient.java


注:本文中的java.util.concurrent.CompletableFuture.handle方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。