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

相关推荐
朝新_2 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir2 小时前
Calendar类日期设置进位问题
java·开发语言
季鸢4 小时前
Java设计模式之状态模式详解
java·设计模式·状态模式
@yanyu6664 小时前
springboot实现查询学生
java·spring boot·后端
ascarl20104 小时前
准确--k8s cgroup问题排查
java·开发语言
magic 2454 小时前
Lombok 的 @Data 注解失效,未生成 getter/setter 方法引发的HTTP 406 错误
java
爱敲代码的憨仔4 小时前
分布式协同自动化办公系统-工作流引擎-流程设计
java·flowable·oa
纪元A梦5 小时前
分布式拜占庭容错算法——PBFT算法深度解析
java·分布式·算法
卿着飞翔5 小时前
RabbitMQ入门4.1.0版本(基于java、SpringBoot操作)
java·rabbitmq·java-rabbitmq
陈阿土i5 小时前
SpringAI 1.0.0 正式版——利用Redis存储会话(ChatMemory)
java·redis·ai·springai