本文整理汇总了Java中java.util.concurrent.CompletableFuture类的典型用法代码示例。如果您正苦于以下问题:Java CompletableFuture类的具体用法?Java CompletableFuture怎么用?Java CompletableFuture使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CompletableFuture类属于java.util.concurrent包,在下文中一共展示了CompletableFuture类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sendAndReceive
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Override
public <M, R> CompletableFuture<R> sendAndReceive(M message,
MessageSubject subject,
Function<M, byte[]> encoder,
Function<byte[], R> decoder,
NodeId toNodeId) {
checkPermission(CLUSTER_WRITE);
try {
ClusterMessage envelope = new ClusterMessage(
clusterService.getLocalNode().id(),
subject,
timeFunction(encoder, subjectMeteringAgent, SERIALIZING).
apply(message));
return sendAndReceive(subject, envelope.getBytes(), toNodeId).
thenApply(bytes -> timeFunction(decoder, subjectMeteringAgent, DESERIALIZING).apply(bytes));
} catch (Exception e) {
return Tools.exceptionalFuture(e);
}
}
示例2: getAmountOfFinishedProcessesBetweenForUser
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Override
public Future<Long> getAmountOfFinishedProcessesBetweenForUser(final LocalDateTime start,
final LocalDateTime end, final Long userId) {
final CompletableFuture<Long> future = new CompletableFuture<>();
final ActorRef analysisActor = getAnalysisActor();
PatternsCS
.ask(analysisActor, new FinishedProcessesInRangeForUserMessage.Request(start, end, userId),
Global.TIMEOUT)
.toCompletableFuture()
.thenApply(obj -> (FinishedProcessesInRangeForUserMessage.Response) obj)
.whenComplete((msg, exc) -> future.complete(msg.getAmount()));
return future;
}
示例3: mockLoader
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
private ProductLoader mockLoader() {
ProductLoader loader = mock(ProductLoader.class);
CompletableFuture<Collection<ProductLinkages>> f = new CompletableFuture<>();
when(loader.getAllProducts()).thenReturn(f);
Thread t = new Thread(() -> {
try {
Thread.sleep(50);
f.complete(ImmutableList.of(
mockProductLinkages(),
mockProductLinkages()
));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
t.start();
return loader;
}
示例4: 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();
}
示例5: stopAsync
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@NotNull
final CompletableFuture<Void> stopAsync(@NotNull CompletableFuture<Void> operation) {
Requires.notNull(operation, "operation");
return Async.runAsync(() -> {
CompletableFuture<Void> dependentOperation = Futures.completedNull();
if (dependentService != null) {
dependentOperation = dependentService.stopAsync(dependentTask);
}
return Async.awaitAsync(
dependentOperation,
() -> {
stopRequested.set();
return Async.usingAsync(
joinableCollection.join(),
() -> Async.awaitAsync(operation));
});
});
}
示例6: closeConnectionAsync
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Override
public CompletionStage<NodeConnectionReport> closeConnectionAsync(
SocketAddress connection, CloseType type) {
Optional<Channel> channel =
this.clientChannelGroup
.stream()
.filter(c -> c.remoteAddress().equals(connection))
.findFirst();
if (channel.isPresent()) {
ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
channelGroup.add(channel.get());
ClusterConnectionReport clusterReport = new ClusterConnectionReport(getCluster().getId());
NodeConnectionReport report =
clusterReport.addNode(this, Collections.singletonList(connection), getAddress());
return closeChannelGroup(channelGroup, type).thenApply(f -> report);
} else {
CompletableFuture<NodeConnectionReport> failedFuture = new CompletableFuture<>();
failedFuture.completeExceptionally(new IllegalArgumentException("Not found"));
return failedFuture;
}
}
示例7: write
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Override
public CompletableFuture<PlcWriteResponse> write(PlcWriteRequest writeRequest) {
curWriteCnt++;
if (writeExceptionTriggerCount > 0 && curWriteCnt == writeExceptionTriggerCount) {
curWriteCnt = 0;
CompletableFuture<PlcWriteResponse> cf = new CompletableFuture<>();
cf.completeExceptionally(new PlcIoException(writeExceptionMsg));
return cf;
}
List<WriteResponseItem> responseItems = new LinkedList<>();
for (WriteRequestItem requestItem : writeRequest.getRequestItems()) {
setDataValue(requestItem.getAddress(), requestItem.getValues());
WriteResponseItem responseItem = new WriteResponseItem(requestItem, ResponseCode.OK);
responseItems.add(responseItem);
}
PlcWriteResponse response = new PlcWriteResponse(writeRequest, responseItems);
return CompletableFuture.completedFuture(response);
}
示例8: relinquishRole
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Override
public CompletableFuture<MastershipEvent> relinquishRole(NodeId nodeId, DeviceId deviceId) {
checkArgument(nodeId != null, NODE_ID_NULL);
checkArgument(deviceId != null, DEVICE_ID_NULL);
if (nodeId.equals(localNodeId)) {
return relinquishLocalRole(deviceId);
}
log.debug("Forwarding request to relinquish "
+ "role for device {} to {}", deviceId, nodeId);
return clusterCommunicator.sendAndReceive(
deviceId,
ROLE_RELINQUISH_SUBJECT,
SERIALIZER::encode,
SERIALIZER::decode,
nodeId);
}
示例9: testMultipleActsResultInAsynchronousActionsFailure
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Test
void testMultipleActsResultInAsynchronousActionsFailure() {
int failuresUntilSuccess = 2;
int numberOfItemsToProcess = 3;
objectUnderTest.failuresUntilSuccess(failuresUntilSuccess);
List<CompletableFuture<Object>> completableFutures = new ArrayList<>();
for (int currentItemIndex = 0; currentItemIndex < numberOfItemsToProcess; currentItemIndex++) {
completableFutures.add(objectUnderTest.actOnItem(new Object()));
}
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture<?>[0])).join();
assertThat(objectUnderTest.timesAsynchronousActionCalled.get())
.isEqualTo((failuresUntilSuccess + 1) * numberOfItemsToProcess);
}
示例10: testDoubleDirectClientChooseBadDirectClient
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Test
public void testDoubleDirectClientChooseBadDirectClient(final TestContext testContext) throws Exception {
final Clients<AsyncClient<? extends Credentials, ? extends CommonProfile>, AsyncAuthorizationGenerator<CommonProfile>> clients = doubleDirectClients();
when(config.getClients()).thenReturn(clients);
final String clientNames = NAME;
when(webContext.getRequestParameter(eq(Clients.DEFAULT_CLIENT_NAME_PARAMETER))).thenReturn(VALUE);
asyncSecurityLogic = new DefaultAsyncSecurityLogic<>(true, true, config, httpActionAdapter);
final Async async = testContext.async();
exception.expect(CompletionException.class);
exception.expectCause(allOf(IsInstanceOf.instanceOf(TechnicalException.class),
hasProperty("message", is("Client not allowed: " + VALUE))));
final CompletableFuture<Object> result = asyncSecurityLogic.perform(webContext, accessGrantedAdapter, clientNames, null, null);
assertSuccessfulEvaluation(result, ExceptionSoftener.softenConsumer(o -> {
assertThat(o, is(nullValue()));
verify(accessGrantedAdapter, times(0)).adapt(webContext);
}), async);
}
示例11: createCategories
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
/**
* This method blocks to create the supplied {@code categoryDrafts} in the CTP project defined by the supplied
* {@code ctpClient},
*
* <p>Note: the method creates the given categories in parallel. So it expects them all to be in the same hierarchy
* level.
*
* @param ctpClient defines the CTP project to create the categories on.
* @param categoryDrafts the drafts to build the categories from.
*/
public static List<Category> createCategories(@Nonnull final SphereClient ctpClient,
@Nonnull final List<CategoryDraft> categoryDrafts) {
final List<CompletableFuture<Category>> futures = new ArrayList<>();
for (CategoryDraft categoryDraft : categoryDrafts) {
final CategoryCreateCommand categoryCreateCommand = CategoryCreateCommand.of(categoryDraft);
final CompletableFuture<Category> categoryCompletableFuture =
ctpClient.execute(categoryCreateCommand).toCompletableFuture();
futures.add(categoryCompletableFuture);
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
.toCompletableFuture().join();
return futures.stream()
.map(CompletableFuture::toCompletableFuture)
.map(CompletableFuture::join)
.collect(Collectors.toList());
}
示例12: test_convertEdgeElementToEdgeMessage_write
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Test
public void test_convertEdgeElementToEdgeMessage_write() throws Exception {
logger.info("[RUN] test_convertEdgeElementToEdgeMessage_write");
String operation = EdgeCommandType.CMD_WRITE.getValue();
EdgeElement element = new EdgeElement(operation);
element.getEdgeAttributeList().add(new EdgeAttribute("value_descriptor",
EdgeFormatIdentifier.STRING_TYPE.getValue(), providerKey));
element.getEdgeAttributeList().add(
new EdgeAttribute("input_argument", EdgeFormatIdentifier.INTEGER_TYPE.getValue(), 100));
CompletableFuture<String> future = null;
EdgeMessage msg = OPCUAMessageHandler.getInstance().convertEdgeElementToEdgeMessage(element,
operation, providerKey, addressable, future);
assertNotNull(msg);
logger.info("[PASS] test_convertEdgeElementToEdgeMessage_write");
}
示例13: removeNodeSpi
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Override
protected void removeNodeSpi() throws BackingStoreException {
log.debug("removeNodeSpi()");
// We need to make this sync. Use doneFuture to sync
CompletableFuture<Void> doneFuture = new CompletableFuture<>();
service.findByNameLike(absolutePath())
.thenAccept(nodes -> {
List<CompletableFuture<Void>> fs = nodes.stream()
.map(service::delete)
.collect(Collectors.toList());
CompletableFuture[] fa = fs.toArray(new CompletableFuture[fs.size()]);
CompletableFuture.allOf(fa)
.thenAccept(v -> doneFuture.complete(null)); // Async
});
try {
doneFuture.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
}
catch (Exception e) {
log.warn("Failed to call removeNodeSpi()", e);
}
}
示例14: should_Cache_failed_fetches
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Test
public void should_Cache_failed_fetches() {
List<Collection<Integer>> loadCalls = new ArrayList<>();
DataLoader<Integer, Object> errorLoader = idLoaderAllExceptions(new DataLoaderOptions(), loadCalls);
CompletableFuture<Object> future1 = errorLoader.load(1);
errorLoader.dispatch();
await().until(future1::isDone);
assertThat(future1.isCompletedExceptionally(), is(true));
assertThat(cause(future1), instanceOf(IllegalStateException.class));
CompletableFuture<Object> future2 = errorLoader.load(1);
errorLoader.dispatch();
await().until(future2::isDone);
assertThat(future2.isCompletedExceptionally(), is(true));
assertThat(cause(future2), instanceOf(IllegalStateException.class));
assertThat(loadCalls, equalTo(singletonList(singletonList(1))));
}
示例15: shouldCallTrustWithoutOptions
import java.util.concurrent.CompletableFuture; //导入依赖的package包/类
@Test
public void shouldCallTrustWithoutOptions() throws Exception {
final TrustOutput output = TrustOutput.builder()
.addTrustedPubkey(TrustedPubkey.builder()
.prefix("")
.key("pubkey1")
.location("")
.build())
.build();
final Response<ByteString> responsePayload =
Response.forPayload(ByteString.of(Json.serialize(output)));
when(client.send(
Request.forUri("http://localhost:8080/api/v0/rkt/trust?pubkey=http://example.com/pubkey1",
DEFAULT_HTTP_METHOD)))
.thenReturn(CompletableFuture.completedFuture(responsePayload));
final TrustOutput response =
rktLauncherRemote.trust("http://example.com/pubkey1").toCompletableFuture().get();
assertEquals(output, response);
}