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

相关推荐
qq_251836457几秒前
基于java Web 个人网站系统设计与实现
java·开发语言·数据库
帅气的你3 分钟前
Spring Boot 1.x 接口性能优化:从 3 秒到 200 毫秒的实战调优之路
java·spring boot
原神启动17 分钟前
K8S(五)—— YAML文件解析
java·容器·kubernetes
周末吃鱼13 分钟前
Lambda作用域
java·开发语言
Wang153016 分钟前
Java异常处理
java·计算机网络
ybb_ymm17 分钟前
@Async修饰不生效
java·前端·数据库
nice_lcj52028 分钟前
数据结构之堆:从概念到应用全解析(附TOP-K经典问题)
java·数据结构·算法
无言(* ̄(エ) ̄)32 分钟前
进程---Linux/C语言
java·开发语言·算法
阿杰 AJie35 分钟前
Token 管理工具
java·spring
Mars酱39 分钟前
1分钟了解响应式编程 | 合适的架构调整
java·后端·响应式编程