parallelStream、CompletableFuture 使用默认ForkJoinPool.commonPool()线程池的问题

parallelStream和CompletableFuture  默认使用的都是 ForkJoinPool.commonPool() 默认线程池;

基于服务器内核的限制,如果你是八核,每次线程只能起八个,不能自定义线程池;

适用于对list密集计算操作充分利用CPU资源,如果需要调用远端服务不建议使用

 

public class StreamUtil {

    public static final int MAX_SEND = 50;

    public static <T> List<List<T>> splitList(List<T> list, int max_send) {
        int limit = (int) Math.ceil((double) list.size() / max_send);
        return Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(i -> list.stream()
                .skip(i * max_send).limit(max_send).parallel().collect(Collectors.toList()))
                .collect(Collectors.toList());
    }
}

List<CompletableFuture> completableFutures = list.stream().map(fix -> CompletableFuture.runAsync(() -> {
            //todo
        },fixAssetPool)).collect(Collectors.toList());

        completableFutures.forEach(CompletableFuture::join);


@Bean("fixAssetPool")
    public ThreadPoolTaskExecutor fixAssetPool(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(40);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("fixAssetPool-future-");
        executor.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());//设置拒绝策略
        return executor;
    }

 

参考:

https://blog.csdn.net/z69183787/article/details/107026179

https://blog.csdn.net/z69183787/article/details/107025668

https://blog.csdn.net/z69183787/article/details/107026232

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值