处理List采用并行流处理时,通过ForkJoinPool来控制并行度失控的问题

在使用parallelStream进行处理list时,如不指定线程池,默认的并行度采用cpu核数进行并行,这里采用ForJoinPool来控制,但循环中使用了redis获取key时,出现失控。具体上代码。

java 复制代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class ForkJoinPoolTest {
    @Resource
    RedisUtils redisUtils;
    @Test
    public void test() {
        ForkJoinPool forkJoinPool = new ForkJoinPool(2);
        List<Integer> fileList = new ArrayList<>();
        for (int i = 1; i < 100; i++) {
            fileList.add(i);
        }
        List<String> result = forkJoinPool.submit(() -> detail(fileList)).join();
    }
    public List<String> detail(List<Integer> fileList){
        return fileList.parallelStream().map(path-> {
            String ocrJson = (String) redisUtils.get("ocr:");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info("第"+path+"张");
            return "第"+path+"张";
        }).collect(Collectors.toList());
    }
}

打印结果:

在这里我已经用ForkJoinPool forkJoinPool = new ForkJoinPool(2);来指定了parallelStream的线程数,但是这里并没有控制住,于是找原因定位到了redis获取key这行代码,将该代码注释后,就可控制parallelStream的并行度。上代码:

java 复制代码
//String ocrJson = (String) redisUtils.get("ocr:");
String ocrJson = "";

这时控制台的打印就为:

在这里,redis采用的是lettuce客户端,经排查可能是因为lettuce是异步客户端,而影响了parallelStream的并行度,具体是因为什么原因导致,待排查。

相关推荐
毕设源码-朱学姐17 小时前
【开题答辩全过程】以 爱心捐赠网站为例,包含答辩的问题和答案
java·eclipse
尘觉19 小时前
中秋节与 Spring Boot 的思考:一场开箱即用的团圆盛宴
java·spring boot·后端
Le1Yu20 小时前
2025-10-7学习笔记
java·笔记·学习
popoxf20 小时前
spring容器启动流程(反射视角)
java·后端·spring
AAA修煤气灶刘哥21 小时前
监控摄像头?不,我们管这个叫优雅的埋点艺术!
java·后端·spring cloud
寻星探路21 小时前
Java EE初阶启程记09---多线程案例(2)
java·开发语言·java-ee
武子康21 小时前
Java-141 深入浅出 MySQL Spring事务失效的常见场景与解决方案详解(3)
java·数据库·mysql·spring·性能优化·系统架构·事务
珹洺21 小时前
Java-Spring入门指南(十五)SpringMVC注解开发
java·spring·microsoft
小满、21 小时前
什么是Maven?关于 Maven 的坐标、依赖管理与 Web 项目构建
java·maven
半旧夜夏1 天前
【设计模式】核心设计模式实战
java·spring boot·设计模式