//创建List集合以存储多个CompletableFuture对象
List<CompletableFuture<JSONObject>> completableFutureList = new ArrayList<>();
//循环向List添加对象
scanList.forEach(scan -> {
    try {
        //尖括号中指定了此future的返回结果为JSONObject类型,即下面的supplyAsync中应当返回一个JSONObject对象
        CompletableFuture<JSONObject> future = CompletableFuture
            //要异步执行的操作放到supplyAsync中执行,getInfo方法返回值为JSONObject类型
                .supplyAsync(() -> sonarService.getInfo(scan.getId()))
            //设置超时时间
                .orTimeout(Constants.CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
            //执行失败,抛出异常
                .exceptionally(e -> {
                    e.printStackTrace();
                    return null;
                });
        completableFutureList.add(future);
    } catch (Exception e) {
        e.printStackTrace();
    }
});
//通过流操作的map来过滤出要的JSONObject对象集合,CompletableFuture::join会阻塞future的线程等待返回结果
List<JSONObject> jsonList = completableFutureList.stream().filter(Objects::nonNull)
        .map(CompletableFuture::join).collect(Collectors.toList());

supplyAsync

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)

Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool.commonPool() with the value obtained by calling the given Supplier.

ForkJoinPool.commonPool() 中执行task,由Supplier提供U值,最终返回一个CompletableFuture<U>对象.

即在supplyAsync中执行的任务会进入一个新的线程中执行,在supplyAsync中执行的任务最终需要返回一个类型为U的数据。ForkJoinPool 类是接口Executor的实现类,ForkJoinPool.commonPool()会返回一个公共的线程池,上面说的新线程就是从这里调用的。

此外,supplyAsync还有重载方法:

supplyAsync(Supplier<U> supplier, Executor executor)

可以看出,重载方法里可以自行指定Executor来执行任务

  • Type Parameters:

U - the function's return type

U 是任务返回的类型,supplyAsync返回的类型是 CompletableFuture<U>

  • Parameters:

supplier - a function returning the value to be used to complete the returned CompletableFuture

supplier 是返回用于完成返回的CompletableFuture的值的函数,()->{ return U;}

  • Returns:

the new CompletableFuture

新的CompletableFuture