处理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的并行度,具体是因为什么原因导致,待排查。

相关推荐
徐同保7 分钟前
python如何手动抛出异常
java·前端·python
极客先躯40 分钟前
高级java每日一道面试题-2025年7月02日-基础篇[LangChain4j]-什么是 AiServices?它是如何简化 LLM 应用开发的?
java·开发语言
摇滚侠1 小时前
JWT 是 token 的一种格式,我的理解对吗?
java·人工智能·intellij-idea·spring ai·springaialibaba
yuuki2332332 小时前
【C++】模拟实现 AVL树
java·c++·算法
牛马baby2 小时前
多态和重载的底层实现原理
java
CircleMouse2 小时前
springboot项目中使用Java 8的日期时间API
java·开发语言·spring boot·后端·spring
Mr YiRan3 小时前
C++语言学习之面向对象
java·c++·学习
dc_00123 小时前
“mysqld --initialize --console ”执行不成功情况总结和解决措施
java
摘星编程3 小时前
解锁Agent智能体的未来:五大实战策略彻底革新人机协作模式
java·开发语言