Java Code Examples for java.util.concurrent.CompletionStage#thenCombine()

The following examples show how to use java.util.concurrent.CompletionStage#thenCombine() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: java-async-util   File:    License: Apache License 2.0 6 votes vote down vote up
private static <T, A, R> CompletionStage<R> collectImpl(
    final Iterator<? extends CompletionStage<T>> it,
    final Collector<? super T, A, R> collector) {

  CompletionStage<A> acc = StageSupport.completedStage(collector.supplier().get());
  final BiConsumer<A, ? super T> accFun = collector.accumulator();

  while (it.hasNext()) {
     * each additional combination step runs only after all previous steps have completed
    acc = acc.thenCombine(, (a, t) -> {
      accFun.accept(a, t);
      return a;
  return collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)
      ? (CompletionStage<R>) acc
      : acc.thenApply(collector.finisher());

Example 2
Source Project: java-async-util   File:    License: Apache License 2.0 6 votes vote down vote up
 * Creates an iterator that is the result of fn applied to iteration elements returned by tIt and
 * uI. If either input iterator terminates, the returned iterator will terminate. If either input
 * iterator returns an exception, an exceptional result will be emitted by the returned iterator.
 * In the case of an exception, a single result will still be consumed from both iterators.
 * <p>
 * When the returned iterator is {@link #close() closed}, the stage returned by close will be
 * complete when both {@code tIt} and {@code uIt} have been closed.
 * @param tIt an AsyncIterator of Ts
 * @param uIt an AsyncIterator of Us
 * @param fn a function that produces a V from a T and a U
 * @return AsyncIterator of fn applied to elements of tIt and uIt
static <T, U, V> AsyncIterator<V> zipWith(
    final AsyncIterator<T> tIt,
    final AsyncIterator<U> uIt,
    final BiFunction<? super T, ? super U, V> fn) {
  // once all futures are complete, if all are nonempty, then apply fn to the arg
  return new AsyncIterator<V>() {
    public CompletionStage<Either<End, V>> nextStage() {
      // call nextStage before checking for an exception
      final CompletionStage<Either<End, T>> tFuture =
      final CompletionStage<Either<End, U>> uFuture =
      return tFuture.thenCombine(uFuture, (et, eu) -> AsyncIterators.zipWith(et, eu, fn));

    public CompletionStage<Void> close() {
      return Combinators
Example 3
Source Project: Java-EE-8-and-Angular   File:    License: MIT License 6 votes vote down vote up
private void random() {
    Client client = ClientBuilder.newClient();
    CompletionStage<Phone> csp ="phones/{item}")
            .resolveTemplate("item", "android")
    CompletionStage<String> csf ="recommendations/{item}")
            .resolveTemplate("item", "android")

    csp.thenCombine(csf, (phone, recommended)
            -> buyWhenAvailableAndRecommended(phone, recommended));
Example 4
Source Project: apicurio-registry   File:    License: Apache License 2.0 5 votes vote down vote up
 * Bulk index operation.
 * @param artifacts the search artifacts
 * @throws Exception for any error
default CompletionStage<SearchResponse> index(List<Search.Artifact> artifacts) throws Exception {
    if (artifacts == null || artifacts.size() == 0) {
        throw new IllegalArgumentException("Empty artifacts!");
    CompletionStage<SearchResponse> cs = index(artifacts.get(0));
    for (int i = 1; i < artifacts.size(); i++) {
        cs = cs.thenCombine(index(artifacts.get(i)), SRFN);
    return cs;
Example 5
public CompletionStage<Boolean> initialize(boolean reset) throws Exception {
    CompletionStage<RestResponse> caches = client.caches();
    RestResponse result = caches.toCompletableFuture().get();
    String body = result.getBody();
    if (result.getStatus() != 200) {
        log.log(Level.SEVERE, body);
        return CompletableFuture.completedFuture(Boolean.FALSE);
    boolean hasProto = cacheExists(body, PROTO_CACHE);
    boolean hasSearch = cacheExists(body, cacheName);
    if (reset) {
        reset(hasProto, PROTO_CACHE, SEARCH_PROTO_KEY);
        reset(hasProto, PROTO_CACHE, COMMON_PROTO_KEY);
        reset(hasSearch, cacheName, null);

    CompletionStage<RestResponse> cs = null;

    if (reset || !hasProto) {
        cs = registerProto(COMMON_PROTO_KEY).thenCompose(r -> registerProto(SEARCH_PROTO_KEY));

    if (reset || !hasSearch) {
        RestEntity configEntity = new StringRestEntityOkHttp(MediaType.APPLICATION_JSON, JSON_CACHE_CONFIG);
        CompletionStage<RestResponse> searchCs = getCache().createWithConfiguration(configEntity);
        cs = (cs != null) ? cs.thenCombine(searchCs, RFN) : searchCs;
    return (cs != null) ? cs.handle((r, t) -> (t == null)) : CompletableFuture.completedFuture(Boolean.TRUE);
Example 6
Source Project: java-async-util   File:    License: Apache License 2.0 5 votes vote down vote up
private static CompletionStage<Void> allOfImpl(
    final Iterator<? extends CompletionStage<?>> it) {
  CompletionStage<Void> accumulator = StageSupport.voidStage();
  while (it.hasNext()) {
    accumulator = accumulator.thenCombine(, (l, r) -> null);
  return accumulator;
Example 7
public static void main(String[] args) {
    final SimpleArgs example = new SimpleArgs();
    CompletionStage<?> f1 = example.testArgs("ABC", Scheduler.interruptible(executor));
    CompletionStage<?> f2 = SimpleArgs.mergeStrings("|", new TaskScheduler(executor), 10);
    f1.thenCombine(f2, (a, b) -> {
        System.out.println("==>" + a);
        System.out.println("==>" + b);
        return "";
Example 8
Source Project: java-async-util   File:    License: Apache License 2.0 4 votes vote down vote up
 * Flattens a Collection of AsyncIterators into a single AsyncIterator.
 * <pre>
 * // returns an AsyncInterator of 0,1,2,3,4
 * {@code
 * AsyncIterators.concat(Arrays.asList(
 *   AsyncIterators.range(0, 3),
 *   AsyncIterators.range(3, 5)))
 * }
 * </pre>
 * Once all elements from an input AsyncIterator have been consumed, {@link #close()} is
 * internally called on that iterator. If this internal call to {@link #close()} produces an
 * exception, an exceptional stage will be included in the returned iterator. It is still
 * necessary to {@link #close()} the returned iterator, as this will close any remaining input
 * iterators (which may be only partially consumed).
 * <p>
 * If {@link #close()} exceptions should be ignored, they should either be squashed in the input
 * iterators or the consumer may use manual {@link #nextStage()} iteration to continue past
 * exceptions.
 * <p>
 * Unlike {@link #concat(Iterator)} and {@link #concat(AsyncIterator)}, closing the returned
 * iterator will additionally close any input iterators that were not encountered during
 * traversal. Because the input is a collection (which is eager unlike iterators) the constituent
 * iterators have likely been initialized and possibly already hold resources. As a convenience,
 * this concatenation will close all input iterators so that their references do not need to be
 * held outside of this concatenation's context. If closing all of the input iterators is not
 * desired, consider using {@link #concat(Iterator)} on the collection's
 * {@link Collection#iterator() iterator}
 * @param asyncIterators a Collection of AsyncIterators to concatenate
 * @return A single AsyncIterator that is the concatenation of asyncIterators
static <T> AsyncIterator<T> concat(final Collection<? extends AsyncIterator<T>> asyncIterators) {
  final Iterator<? extends AsyncIterator<T>> iter = asyncIterators.iterator();
  if (!iter.hasNext()) {
    return AsyncIterator.empty();

  return new AsyncIterators.ConcatAsyncIterator<T>(iter) {
    public CompletionStage<Void> close() {
      final CompletionStage<Void> superClose = super.close();
      if (iter.hasNext()) {
        final Collection<CompletionStage<Void>> remainingIters = new ArrayList<>();
        do {
        } while (iter.hasNext());
        return superClose.thenCombine(Combinators.allOf(remainingIters), (ig1, ig2) -> null);
      } else {
        return superClose;