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


Java CompletableFuture類代碼示例

本文整理匯總了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);
    }
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:20,代碼來源:ClusterCommunicationManager.java

示例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;
}
 
開發者ID:stefanstaniAIM,項目名稱:IPPR2016,代碼行數:17,代碼來源:ProcessServiceImpl.java

示例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;
}
 
開發者ID:cloudwall,項目名稱:libcwfincore,代碼行數:19,代碼來源:LoadableProductMasterTest.java

示例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();
}
 
開發者ID:tunnelvisionlabs,項目名稱:java-threading,代碼行數:23,代碼來源:TestBase.java

示例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));
            });
    });
}
 
開發者ID:tunnelvisionlabs,項目名稱:java-threading,代碼行數:21,代碼來源:JoinableFutureTest.java

示例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;
  }
}
 
開發者ID:datastax,項目名稱:simulacron,代碼行數:24,代碼來源:BoundNode.java

示例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);
}
 
開發者ID:apache,項目名稱:incubator-plc4x,代碼行數:19,代碼來源:MockConnection.java

示例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);
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:19,代碼來源:ConsistentDeviceMastershipStore.java

示例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);
}
 
開發者ID:CMSgov,項目名稱:qpp-conversion-tool,代碼行數:18,代碼來源:AnyOrderAsyncActionServiceTest.java

示例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);

}
 
開發者ID:millross,項目名稱:pac4j-async,代碼行數:20,代碼來源:DefaultAsyncSecurityLogicTest.java

示例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());
}
 
開發者ID:commercetools,項目名稱:commercetools-sync-java,代碼行數:28,代碼來源:CategoryITUtils.java

示例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");
}
 
開發者ID:mgjeong,項目名稱:device-opcua-java,代碼行數:18,代碼來源:OPCUAMessageHandlerTest.java

示例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);
    }
}
 
開發者ID:mbari-media-management,項目名稱:vars-annotation,代碼行數:23,代碼來源:WebPreferences.java

示例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))));
}
 
開發者ID:bbakerman,項目名稱:java-dataloader,代碼行數:22,代碼來源:DataLoaderTest.java

示例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);
}
 
開發者ID:honnix,項目名稱:rkt-launcher,代碼行數:20,代碼來源:SystemTest.java


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