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


Java CompletableFuture.get方法代碼示例

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


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

示例1: sendMultisigSignatureTransaction

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
 * Send multisig signature transaction.
 *
 * @param transaction
 *            the transaction
 * @return the nem announce result
 */
public static NemAnnounceResult sendMultisigSignatureTransaction(MultisigSignatureTransaction transaction) {

	final byte[] data = BinarySerializer.serializeToBytes(transaction.asNonVerifiable());

	final RequestAnnounce request = new RequestAnnounce(data, transaction.getSignature().getBytes());
	final CompletableFuture<Deserializer> future = TransactionApi.announceTransaction(NemAppsLibGlobals.getNodeEndpoint(),
			request);
	try {
		Deserializer transDes = future.get();
		return new NemAnnounceResult(transDes);
	} catch (Exception e) {
		LOGGER.warning("Error Occured: " + e.getMessage());
	}
	return null;
}
 
開發者ID:NEMPH,項目名稱:nem-apps-lib,代碼行數:23,代碼來源:TransactionSenderUtil.java

示例2: testSetInlinesContinuationsUnderSwitch

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
 * Verifies that inlining continuations works when the option is set.
 */
@Test
public void testSetInlinesContinuationsUnderSwitch() throws Exception {
	event = new AsyncAutoResetEvent(/*allowInliningAwaiters:*/true);
	Thread settingThread = Thread.currentThread();
	final AtomicBoolean setReturned = new AtomicBoolean(false);
	CompletableFuture<Void> inlinedContinuation = event.waitAsync().whenComplete((result, exception) -> {
		// Arrange to synchronously block the continuation until set() has returned,
		// which would deadlock if set() does not return until inlined continuations complete.
		Assert.assertFalse(setReturned.get());
		Assert.assertSame(settingThread, Thread.currentThread());
	});

	event.set();
	setReturned.set(true);
	Assert.assertTrue(inlinedContinuation.isDone());
	// rethrow any exceptions in the continuation
	inlinedContinuation.get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
}
 
開發者ID:tunnelvisionlabs,項目名稱:java-threading,代碼行數:22,代碼來源:AsyncAutoResetEventTest.java

示例3: cannotCreateALoanWithoutAction

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void cannotCreateALoanWithoutAction()
  throws MalformedURLException,
  InterruptedException,
  ExecutionException,
  TimeoutException {

  JsonObject loanRequest = new LoanRequestBuilder().create();

  loanRequest.remove("action");

  CompletableFuture<JsonResponse> createCompleted = new CompletableFuture();

  client.post(loanStorageUrl(), loanRequest, StorageTestSuite.TENANT_ID,
    ResponseHandler.json(createCompleted));

  JsonResponse response = createCompleted.get(5, TimeUnit.SECONDS);

  assertThat(String.format("Creating the loan should fail: %s", response.getBody()),
    response.getStatusCode(), is(UNPROCESSABLE_ENTITY));
}
 
開發者ID:folio-org,項目名稱:mod-circulation-storage,代碼行數:22,代碼來源:LoansApiTest.java

示例4: after

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@AfterClass
public static void after()
  throws InterruptedException, ExecutionException,
  TimeoutException, MalformedURLException {

  removeTenant(TENANT_ID);

  CompletableFuture undeploymentComplete = new CompletableFuture<String>();

  vertx.close(res -> {
    if(res.succeeded()) {
      undeploymentComplete.complete(null);
    }
    else {
      undeploymentComplete.completeExceptionally(res.cause());
    }
  });

  undeploymentComplete.get(20, TimeUnit.SECONDS);
}
 
開發者ID:folio-org,項目名稱:mod-circulation-storage,代碼行數:21,代碼來源:StorageTestSuite.java

示例5: run3

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
 * 3.
 */
public void run3() throws InterruptedException, ExecutionException {
    /**使用supplyAsync()函數執行一個異步任務。接著連續使用流式調用對任務的處理結果進行再加工,直到最後的結果輸出。*/
    CompletableFuture<Void> fu = CompletableFuture
            .supplyAsync(() -> calc(50))
            .thenApply((i) -> Integer.toString(i))
            .thenApply((str) -> "\"" + str + "\"")
            .thenAccept(System.out::println);
    /**等待計算完成*/
    fu.get();

}
 
開發者ID:zhangboqing,項目名稱:multithread,代碼行數:15,代碼來源:CompletableFutureDemo.java

示例6: cannotUpdateALoanWithInvalidDates

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void cannotUpdateALoanWithInvalidDates()
  throws InterruptedException,
  MalformedURLException,
  TimeoutException,
  ExecutionException {

  IndividualResource loan = createLoan(loanRequest());

  JsonObject returnedLoan = loan.copyJson();

  returnedLoan.put("loanDate", "bar");
  returnedLoan.put("returnDate", "foo");

  CompletableFuture<TextResponse> putCompleted = new CompletableFuture();

  client.put(loanStorageUrl(String.format("/%s", loan.getId())), returnedLoan,
    StorageTestSuite.TENANT_ID, ResponseHandler.text(putCompleted));

  TextResponse response = putCompleted.get(5, TimeUnit.SECONDS);

  assertThat(String.format("Should have failed to update loan: %s", response.getBody()),
    response.getStatusCode(), is(HttpURLConnection.HTTP_BAD_REQUEST));

  assertThat(response.getBody(),
    containsString("loan date must be a date time (in RFC3339 format)"));

  assertThat(response.getBody(),
    containsString("return date must be a date time (in RFC3339 format)"));
}
 
開發者ID:folio-org,項目名稱:mod-circulation-storage,代碼行數:31,代碼來源:LoansApiTest.java

示例7: putResponse

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private JsonResponse putResponse(LoanRules loanRules) throws Exception {
  CompletableFuture<JsonResponse> createCompleted = new CompletableFuture<>();
  client.put(loanRulesStorageUrl(),
    loanRules, StorageTestSuite.TENANT_ID,
    ResponseHandler.json(createCompleted));
  return createCompleted.get(5, TimeUnit.SECONDS);
}
 
開發者ID:folio-org,項目名稱:mod-circulation-storage,代碼行數:8,代碼來源:LoanRulesApiTest.java

示例8: testWatchWithIdentityQuery

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test(timeout = 10000)
public void testWatchWithIdentityQuery() throws Exception {
    final Revision rev1 = repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, textUpserts[0]).join();

    CompletableFuture<QueryResult<Object>> f =
            repo.watch(rev1, Query.identity(textPaths[0]));

    final Revision rev2 = repo.commit(HEAD, 0L, Author.UNKNOWN, SUMMARY, textPatches[1]).join();
    final QueryResult<Object> res = f.get(3, TimeUnit.SECONDS);
    assertThat(res.revision()).isEqualTo(rev2);
    assertThat(res.type()).isEqualTo(EntryType.TEXT);
    // Text must be sanitized so that the last line ends with \n.
    assertThat(res.content()).isEqualTo(textUpserts[1].content() + '\n');
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:15,代碼來源:GitRepositoryTest.java

示例9: canCreateOpenLoanWhenClosedLoansForSameItem

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void canCreateOpenLoanWhenClosedLoansForSameItem()
  throws InterruptedException,
  MalformedURLException,
  TimeoutException,
  ExecutionException {

  UUID itemId = UUID.randomUUID();

  JsonObject closedLoanRequest = new LoanRequestBuilder()
    .withItemId(itemId)
    .withStatus("Closed")
    .create();

  createLoan(closedLoanRequest);

  JsonObject openLoanRequest = new LoanRequestBuilder()
    .withItemId(itemId)
    .withStatus("Open")
    .create();

  CompletableFuture<JsonResponse> createCompleted = new CompletableFuture<>();

  client.post(loanStorageUrl(), openLoanRequest, StorageTestSuite.TENANT_ID,
    ResponseHandler.json(createCompleted));

  JsonResponse response = createCompleted.get(5, TimeUnit.SECONDS);

  assertThat(String.format("Creating the loan should succeed: %s", response.getBody()),
    response.getStatusCode(), is(HttpURLConnection.HTTP_CREATED));
}
 
開發者ID:folio-org,項目名稱:mod-circulation-storage,代碼行數:32,代碼來源:LoansApiTest.java

示例10: canSortByNameDescending

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void canSortByNameDescending()
  throws InterruptedException,
  MalformedURLException,
  TimeoutException,
  ExecutionException,
  UnsupportedEncodingException {

  createFixedDueDateSchedule(createFixedDueDate("quarterly"));
  createFixedDueDateSchedule(createFixedDueDate("semester"));
  createFixedDueDateSchedule(createFixedDueDate("semester2"));

  URL sortUrl = dueDateURL("?query=name=*"
    + URLEncoder.encode(" sortBy name/sort.descending", "UTF-8"));

  CompletableFuture<JsonResponse> getCompleted = new CompletableFuture<>();

  client.get(sortUrl, StorageTestSuite.TENANT_ID,
    ResponseHandler.json(getCompleted));

  JsonResponse getResponse = getCompleted.get(5, TimeUnit.SECONDS);

  assertThat(String.format("Failed to get fixed due date schedules: %s",
    getResponse.getJson().encodePrettily()),
    getResponse.getStatusCode(), is(HttpURLConnection.HTTP_OK));

  List<JsonObject> results = JsonArrayHelper.toList(getResponse.getJson()
    .getJsonArray("fixedDueDateSchedules"));

  assertThat(results.size(), is(3));
  assertThat(results.get(0).getString("name"), is("semester2"));
  assertThat(results.get(2).getString("name"), is("quarterly"));
}
 
開發者ID:folio-org,項目名稱:mod-circulation-storage,代碼行數:34,代碼來源:FixedDueDateApiTest.java

示例11: ensureConstN

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Benchmark
public Void ensureConstN() throws InterruptedException, ExecutionException {
  CompletableFuture<Void> f = constVoidFuture;
  for (int i = 0; i < N.n; i++)
    f = f.thenRun(ensureF);
  return f.get();
}
 
開發者ID:traneio,項目名稱:future,代碼行數:8,代碼來源:JavaSyncFutureBenchmark.java

示例12: testWatchWithQuery

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void testWatchWithQuery() throws Exception {
    final Revision rev1 = repo.commit(
            HEAD, 0L, Author.UNKNOWN, SUMMARY,
            Change.ofJsonUpsert(jsonPaths[0], "{ \"hello\": \"mars\" }")).join();

    CompletableFuture<QueryResult<JsonNode>> f =
            repo.watch(rev1, Query.ofJsonPath(jsonPaths[0], "$.hello"));

    // Make sure the initial change does not trigger a notification.
    assertThatThrownBy(() -> f.get(500, TimeUnit.MILLISECONDS))
            .isInstanceOf(TimeoutException.class);

    // Make sure the change that does not affect the query result does not trigger a notification.
    repo.commit(
            HEAD, 0L, Author.UNKNOWN, SUMMARY,
            Change.ofJsonUpsert(jsonPaths[0], "{ \"hello\": \"mars\", \"goodbye\": \"venus\" }"));

    assertThatThrownBy(() -> f.get(500, TimeUnit.MILLISECONDS))
            .isInstanceOf(TimeoutException.class);

    // Here comes the interesting change; make sure notification is triggered.
    final Revision rev3 = repo.commit(
            HEAD, 0L, Author.UNKNOWN, SUMMARY,
            Change.ofJsonUpsert(jsonPaths[0], "{ \"hello\": \"jupiter\", \"goodbye\": \"mars\" }")).join();

    final QueryResult<JsonNode> res = f.get(3, TimeUnit.SECONDS);
    assertThat(res.revision()).isEqualTo(rev3);
    assertThat(res.type()).isEqualTo(EntryType.JSON);
    assertThat(res.content()).isEqualTo(TextNode.valueOf("jupiter"));
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:32,代碼來源:GitRepositoryTest.java

示例13: flatMapPromise

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Benchmark
public String flatMapPromise() throws InterruptedException, ExecutionException {
  CompletableFuture<String> p = new CompletableFuture<String>();
  p.thenComposeAsync(flatMapF);
  p.complete(string);
  return p.get();
}
 
開發者ID:traneio,項目名稱:future,代碼行數:8,代碼來源:JavaAsyncFutureBenchmark.java

示例14: canSortDifferentCaseNamesAscending

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Ignore("Fails on Mac OS due to differences in UTF-8 collation libraries")
@Test
public void canSortDifferentCaseNamesAscending()
  throws InterruptedException,
  MalformedURLException,
  TimeoutException,
  ExecutionException,
  UnsupportedEncodingException {

  createFixedDueDateSchedule(createFixedDueDate("quarterly"));
  createFixedDueDateSchedule(createFixedDueDate("Semester"));
  createFixedDueDateSchedule(createFixedDueDate("semester2"));

  URL sortUrl = dueDateURL("?query=name=*"
    + URLEncoder.encode(" sortBy name/sort.ascending", "UTF-8"));

  CompletableFuture<JsonResponse> getCompleted = new CompletableFuture<>();

  client.get(sortUrl, StorageTestSuite.TENANT_ID,
    ResponseHandler.json(getCompleted));

  JsonResponse getResponse = getCompleted.get(5, TimeUnit.SECONDS);

  assertThat(String.format("Failed to get fixed due date schedules: %s",
    getResponse.getJson().encodePrettily()),
    getResponse.getStatusCode(), is(HttpURLConnection.HTTP_OK));

  List<JsonObject> results = JsonArrayHelper.toList(getResponse.getJson()
    .getJsonArray("fixedDueDateSchedules"));

  results.stream()
    .map(result -> result.getString("name"))
    .forEachOrdered(System.out::println);

  assertThat(results.size(), is(3));
  assertThat(results.get(0).getString("name"), is("quarterly"));
}
 
開發者ID:folio-org,項目名稱:mod-circulation-storage,代碼行數:38,代碼來源:FixedDueDateApiTest.java

示例15: bodyFailure

import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test public void bodyFailure() throws Exception {
  server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));

  CompletableFuture<String> future = service.body();
  try {
    future.get();
    fail();
  } catch (ExecutionException e) {
    assertThat(e.getCause()).isInstanceOf(IOException.class);
  }
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:12,代碼來源:CompletableFutureTest.java


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