Java-CompletableFuture结合批处理、自定义线程池

将 CompletableFuture 与批处理和自定义线程池结合使用是一种常见的模式,用于高效地管理和执

行批量异步任务。下面是一个具体的示例,展示了如何使用 CompletableFuture 和自定义线程池来

执行批量异步任务,并在主线程中获取结果。

import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class CompletableFutureBatchProcessingExample {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 创建一个自定义线程池
        ExecutorService customThreadPool = Executors.newFixedThreadPool(4);

        // 创建一个数据列表
        List<Integer> data = IntStream.rangeClosed(1, 100).boxed().collect(Collectors.toList());

        // 执行批处理
        CompletableFuture<Void> future = batchProcessWithFuture(data, 10, customThreadPool, bat
### 关系及用法 #### CompletableFuture线程池的关系 CompletableFutureJava 中用于实现异步编程的一个强大工具,它允许执行非阻塞的任务,并提供了多种方法来组合多个异步操作。然而,默认情况下,CompletableFuture 的任务可能会由 ForkJoinPool.commonPool() 来执行,这可能不是最优的选择,特别是在高负载的应用程序中[^1]。 为了更好地控制并发行为以及资源管理,通常建议将 CompletableFuture自定义线程池一起使用。这样做不仅能够提升性能,还能更灵活地调整线程数量和其他参数设置,从而适应不同的应用场景需求[^2]。 #### 使用线程池的方式 当希望指定特定的 ExecutorService (即线程池) 给某个 CompletableFuture 实例时,可以通过 `supplyAsync` 或者 `runAsync` 方法传递该 executor 参数。这样做的好处是可以精确配置参与计算过程中的工作线程数目以及其他属性,比如队列容量等。 下面是创建带有自定义线程池 completable future 的简单例子: ```java import java.util.concurrent.*; public class CustomThreadPoolExample { public static void main(String[] args) throws InterruptedException, ExecutionException { // 创建固定大小为4的工作线程池 ExecutorService customExecutor = Executors.newFixedThreadPool(4); // 使用 supplyAsync 提交有返回值的任务给定executor运行 CompletableFuture<String> futureWithResult = CompletableFuture.supplyAsync(() -> "Task Result", customExecutor); System.out.println(futureWithResult.get()); // 清理资源 customExecutor.shutdown(); } } ``` 对于批处理场景下的大量异步请求,则可以考虑如下方式构建链式调用来优化效率: ```java import java.util.List; import java.util.stream.Collectors; import java.util.concurrent.*; import java.util.Arrays; class BatchProcessingExample { private final ExecutorService threadPool = Executors.newCachedThreadPool(); List<CompletableFuture<Void>> processBatch(List<Integer> ids){ return ids.stream() .map(id -> CompletableFuture.runAsync( () -> performOperation(id), this.threadPool)) .collect(Collectors.toList()); } void waitForAllToComplete(List<CompletableFuture<Void>> futures)throws Exception{ CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); } private void performOperation(Integer id){ try { Thread.sleep((long)(Math.random()*100)); } catch(Exception e){} System.out.println("Processed ID: "+id+" by "+Thread.currentThread().getName()); } public static void main(String[]args)throws Exception{ new BatchProcessingExample().processBatch(Arrays.asList(1,2,3)).forEach(System.out::println); } } ``` 上述代码片段展示了如何利用流 API 将一系列整数映射成对应的 CompletableFutures 集合,并最终等待所有这些 Future 完成后再继续执行后续逻辑。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZHOU_VIP

您的鼓励将是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值