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

相关推荐
爱上语文12 分钟前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
serve the people15 分钟前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端
qmx_071 小时前
HTB-Jerry(tomcat war文件、msfvenom)
java·web安全·网络安全·tomcat
为风而战1 小时前
IIS+Ngnix+Tomcat 部署网站 用IIS实现反向代理
java·tomcat
技术无疆3 小时前
快速开发与维护:探索 AndroidAnnotations
android·java·android studio·android-studio·androidx·代码注入
架构文摘JGWZ6 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
拾光师7 小时前
spring获取当前request
java·后端·spring
aPurpleBerry7 小时前
neo4j安装启动教程+对应的jdk配置
java·neo4j
我是苏苏7 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言
xujinwei_gingko7 小时前
Spring IOC容器Bean对象管理-Java Config方式
java·spring