相关疑难解决方法(0)

列出<Future>到Future <List>序列

我想转换List<CompletableFuture<X>>CompletableFuture<List<T>>.这非常有用,因为当您有许多异步任务并且需要获得所有异步任务的结果时.

如果其中任何一个失败,则最终的未来将失败.这就是我实施的方式:

  public static <T> CompletableFuture<List<T>> sequence2(List<CompletableFuture<T>> com, ExecutorService exec) {
        if(com.isEmpty()){
            throw new IllegalArgumentException();
        }
        Stream<? extends CompletableFuture<T>> stream = com.stream();
        CompletableFuture<List<T>> init = CompletableFuture.completedFuture(new ArrayList<T>());
        return stream.reduce(init, (ls, fut) -> ls.thenComposeAsync(x -> fut.thenApplyAsync(y -> {
            x.add(y);
            return x;
        },exec),exec), (a, b) -> a.thenCombineAsync(b,(ls1,ls2)-> {
            ls1.addAll(ls2);
            return ls1;
        },exec));
    }
Run Code Online (Sandbox Code Playgroud)

要运行它:

ExecutorService executorService = Executors.newCachedThreadPool();
        Stream<CompletableFuture<Integer>> que = IntStream.range(0,100000).boxed().map(x -> CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep((long) (Math.random() * 10));
            } catch (InterruptedException e) {
                e.printStackTrace(); …
Run Code Online (Sandbox Code Playgroud)

java concurrency java-8 completable-future

67
推荐指数
5
解决办法
3万
查看次数

标签 统计

completable-future ×1

concurrency ×1

java ×1

java-8 ×1