Java Thread Future sequence(List> futures)

Here you can find the source of sequence(List> futures)

Description

sequence

License

Open Source License

Declaration

public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) 

Method Source Code


//package com.java2s;
/*/*from   w  w  w  .  j  a  va 2 s  .  c  o m*/
 * Copyright (c) 2016 Kevin Herron
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *    http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *    http://www.eclipse.org/org/documents/edl-v10.html.
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class Main {
    public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) {
        if (futures.isEmpty()) {
            return CompletableFuture.completedFuture(Collections.emptyList());
        }

        CompletableFuture[] fa = futures.toArray(new CompletableFuture[futures.size()]);

        return CompletableFuture.allOf(fa).thenApply(v -> {
            List<T> results = new ArrayList<>(futures.size());

            for (CompletableFuture<T> cf : futures) {
                results.add(cf.join());
            }

            return results;
        });
    }

    public static <T> CompletableFuture<List<T>> sequence(CompletableFuture<T>[] futures) {
        if (futures.length == 0) {
            return CompletableFuture.completedFuture(Collections.emptyList());
        }

        return CompletableFuture.allOf(futures).thenApply(v -> {
            List<T> results = new ArrayList<>(futures.length);

            for (CompletableFuture<T> cf : futures) {
                results.add(cf.join());
            }

            return results;
        });
    }
}

Related

  1. runIfNotDoneAndGet(RunnableFuture future)
  2. runInNewThread(String threadName, Runnable target)
  3. sequence(List> futures)
  4. sequence(List> futures)
  5. sequence(List> futures)
  6. submitTasks(ExecutorCompletionService ecs, Iterable> tasks)
  7. sumFutures(List> futures)
  8. transferResult(final CompletionStage source, final CompletableFuture target)
  9. transferResult(final CompletionStage source, final CompletableFuture target)