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

相关推荐
devilnumber7 分钟前
如何在java的Lambda中安全地修改外部变量?
java·安全·lambda
大得3697 分钟前
langchain使用
java·python·langchain
带刺的坐椅8 分钟前
SolonCode CLI 的心智记忆功能:让 AI 编程助手越用越懂你
java·ai·llm·cli·soloncode
我命由我1234518 分钟前
Visual Studio - Visual Studio 注释快捷键
java·c语言·开发语言·c++·ide·java-ee·visual studio
lemon_sjdk26 分钟前
DecimalFormat
java·开发语言·python
Nontee29 分钟前
一、Java 基础 面试题解答(72题)
java·开发语言
兰令水30 分钟前
topcode【随机算法题】【2026.5.16打卡-java版本】
java·数据结构·算法
摇滚侠31 分钟前
SpringBoot 面试题 真正的 offer 偏方 Java 基础 Java 高级
java·spring boot·后端
AI人工智能+电脑小能手36 分钟前
【大白话说Java面试题 第58题】【JVM篇】第18题:讲一下三色标记
java·开发语言·jvm
huaiixinsi36 分钟前
Java 后端面试高频题整理(02)
java·开发语言·spring·面试·职场和发展·架构·maven