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

相关推荐
9677几秒前
Java 类映射数据库表的核心规则
java·数据库·oracle
阳光下的米雪5 分钟前
存储过程的使用以及介绍
java·服务器·数据库·pgsql
yoyo_zzm7 分钟前
Spring Boot 各种事务操作实战(自动回滚、手动回滚、部分回滚)
java·数据库·spring boot
tuyanfei12 分钟前
Spring 简介
java·后端·spring
遥遥晚风点点13 分钟前
JAVA http请求报错:unable to find valid certification path to requested target
java·网络·网络协议·http
ZhengEnCi13 分钟前
J0A-JPA持久化技术专栏链接目录
java·数据库
代码探秘者15 分钟前
【大模型应用】2.RAG详细流程
java·开发语言·人工智能·后端·python
xieliyu.19 分钟前
Java :类和对象(一)
java·开发语言
xuboyok228 分钟前
Spring Boot管理用户数据
java·spring boot·后端
阳光下的米雪37 分钟前
记一次pgsql中with as语法的使用以及with as介绍
java·数据库