@Override public CompletableFuture<V> completable() { if (this.executionException != null) { CompletableFuture<V> completable = new CompletableFuture<>(); completable.completeExceptionally(exposedException(this.executionException)); return completable; } else { return CompletableFuture.completedFuture(this.value); } }
@RequestMapping(params = "completableFutureWithImmediateValue") public CompletableFuture<Person> getCompletableFutureWithImmediateValue() { CompletableFuture<Person> future = new CompletableFuture<>(); future.complete(new Person("Joe")); return future; }
@Override @SuppressWarnings("unchecked") public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { return super.get(timeout, unit); } catch (TimeoutException | ExecutionException | InterruptedException e) { throw e; } catch (Throwable e) { throw new RpcException(e); } }
/** Returns if the future has successfully completed. */ static boolean isReady(@Nullable CompletableFuture<?> future) { return (future != null) && future.isDone() && !future.isCompletedExceptionally() && (future.join() != null); }
@Override public void onResponse(Call<R> call, Response<R> response) { if (response.isSuccessful()) { future.complete(response.body()); } else { future.completeExceptionally(new HttpException(response)); } }
private static List<JobID> getRunningJobs(ClusterClient<?> client) throws Exception { Collection<JobStatusMessage> statusMessages = client.listJobs().get(); return statusMessages.stream() .filter(status -> !status.getJobState().isGloballyTerminalState()) .map(JobStatusMessage::getJobId) .collect(Collectors.toList()); }
@Override public CompletableFuture<Boolean> containsAll(Collection<? extends String> keys) { Map<PartitionId, Collection<String>> partitions = Maps.newHashMap(); keys.forEach(key -> partitions.computeIfAbsent(getProxyClient().getPartitionId(key), k -> Lists.newArrayList()).add(key)); return Futures.allOf(partitions.entrySet().stream() .map(entry -> getProxyClient() .applyOn(entry.getKey(), service -> service.containsKeys(entry.getValue()))) .collect(Collectors.toList())) .thenApply(results -> results.stream().reduce(Boolean::logicalAnd).orElse(false)); }
@Test void updateIndexOnAddShouldUpdateFirstUnseenWhenUnseen() { MailboxMessage message = mock(MailboxMessage.class); when(message.createFlags()).thenReturn(new Flags()); when(message.getUid()).thenReturn(MESSAGE_UID); testee.updateIndexOnAdd(message, MAILBOX_ID).join(); Optional<MessageUid> actual = firstUnseenDAO.retrieveFirstUnread(MAILBOX_ID).join(); assertThat(actual.isPresent()).isTrue(); assertThat(actual.get()).isEqualTo(MESSAGE_UID); }
@BeforeClass public static void setUp() throws Exception { UTIL.startMiniCluster(1); UTIL.createTable(TABLE_NAME, FAMILY); CONN = ConnectionFactory.createAsyncConnection(UTIL.getConfiguration()).get(); TABLE = CONN.getTable(TABLE_NAME); TABLE.putAll(IntStream.range(0, ROW_COUNT).mapToObj(i -> { Put put = new Put(Bytes.toBytes(i)); IntStream.range(0, CQS.length) .forEach(j -> put.addColumn(FAMILY, CQS[j], Bytes.toBytes((j + 1) * i))); return put; }).collect(Collectors.toList())).get(); }
@Override public CompletableFuture<List<RegionInfo>> getRegions(TableName tableName) { if (tableName.equals(META_TABLE_NAME)) { return connection.getLocator().getRegionLocation(tableName, null, null, operationTimeoutNs) .thenApply(loc -> Collections.singletonList(loc.getRegion())); } else { return AsyncMetaTableAccessor.getTableHRegionLocations(metaTable, Optional.of(tableName)) .thenApply( locs -> locs.stream().map(loc -> loc.getRegion()).collect(Collectors.toList())); } }
public static <R> CompletableFuture<List<R>> sequenceSuccessFuture(List<CompletableFuture<R>> futures) { return CompletableFuture.supplyAsync(() -> futures.parallelStream() .map(AsyncUtils::getValue) .filter(Objects::nonNull) .collect(Collectors.toList()) ); }
default List<MessageHeaders> getSpecs() { Comparator<String> comparator = new RestServerEndpoint.RestHandlerUrlComparator.CaseInsensitiveOrderComparator(); return initializeHandlers(CompletableFuture.completedFuture(null)).stream() .map(tuple -> tuple.f0) .filter(spec -> spec instanceof MessageHeaders) .map(spec -> (MessageHeaders) spec) .sorted((spec1, spec2) -> comparator.compare(spec1.getTargetRestEndpointURL(), spec2.getTargetRestEndpointURL())) .collect(Collectors.toList()); } }
@Test @SuppressWarnings("unchecked") public void introFutureHell() { CompletableFuture<List<String>> ids = ifhIds(); // <1> CompletableFuture<List<String>> result = ids.thenComposeAsync(l -> { // <2> Stream<CompletableFuture<String>> zip = l.stream().map(i -> { // <3> CompletableFuture<String> nameTask = ifhName(i); // <4> CompletableFuture<Integer> statTask = ifhStat(i); // <5> return nameTask.thenCombineAsync(statTask, (name, stat) -> "Name " + name + " has stats " + stat); // <6> }); List<CompletableFuture<String>> combinationList = zip.collect(Collectors.toList()); // <7> CompletableFuture<String>[] combinationArray = combinationList.toArray(new CompletableFuture[combinationList.size()]); CompletableFuture<Void> allDone = CompletableFuture.allOf(combinationArray); // <8> return allDone.thenApply(v -> combinationList.stream() .map(CompletableFuture::join) // <9> .collect(Collectors.toList())); }); List<String> results = result.join(); // <10> assertThat(results).contains( "Name NameJoe has stats 103", "Name NameBart has stats 104", "Name NameHenry has stats 105", "Name NameNicole has stats 106", "Name NameABSLAJNFOAJNFOANFANSF has stats 121"); }
@Test public void testMultiSessionSparkContextReUse() throws MalformedURLException { String confDir = "../data/conf/spark/local/hive-site.xml"; HiveConf.setHiveSiteLocation(new File(confDir).toURI().toURL()); ExecutorService executor = Executors.newFixedThreadPool(barrier.getParties()); List<CompletableFuture<Void>> futures = IntStream.range(0, barrier.getParties()).boxed() .map(i -> CompletableFuture.supplyAsync(() -> execute(i), executor)) .collect(Collectors.toList()); futures.forEach(CompletableFuture::join); }
@Test(timeout = 10000) public void testSpanInThreadPoolHasSameTraceId() throws Exception { poolHttpClient.get("pool").aggregate().get(); final Span[] spans = spanReporter.take(5); assertThat(Arrays.stream(spans).map(Span::traceId).collect(toImmutableSet())).hasSize(1); assertThat(Arrays.stream(spans).map(Span::parentId) .filter(Objects::nonNull) .collect(toImmutableSet())).hasSize(1); }
@Test public void thenFlatComposeOnOptionalShouldTransformUnderlyingValuesAndComposeFuturesWithOptionalUnboxing() { assertThat( FluentFutureStream.of( CompletableFuture.completedFuture( Stream.of(1, 2, 3))) .thenFlatComposeOnOptional(i -> CompletableFuture.completedFuture(Optional.of(i + 1) .filter(j -> j % 2 == 0))) .join() .collect(Guavate.toImmutableList())) .containsExactly(2, 4); }
private static int getNumberOfSlotsPerTaskManager(final String host, final int port) throws Exception { final TaskManagersInfo taskManagersInfo = restClient.sendRequest( host, port, TaskManagersHeaders.getInstance()).get(); return taskManagersInfo.getTaskManagerInfos() .stream() .map(TaskManagerInfo::getNumberSlots) .findFirst() .orElse(0); }
@Test void chainAllShouldPreserveOrder() { int itemCount = 10; ImmutableList<Integer> ints = IntStream.range(0, itemCount) .boxed() .collect(Guavate.toImmutableList()); Stream<Integer> result = CompletableFutureUtil.chainAll(ints.stream(), i -> CompletableFuture.supplyAsync(() -> i, executorService)) .join(); assertThat(result.collect(Guavate.toImmutableList())) .containsExactlyElementsOf(ints); }
private void failAll(Stream<Action> actions, int tries) { actions.forEach(action -> { CompletableFuture<T> future = action2Future.get(action); if (future.isDone()) { return; } future.completeExceptionally(new RetriesExhaustedException(tries, Optional.ofNullable(removeErrors(action)).orElse(Collections.emptyList()))); }); }