当前位置: 首页>>代码示例>>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;未经允许,请勿转载。