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

相关推荐
前行的小黑炭10 分钟前
Android 协程的使用:结合一个环境噪音检查功能的例子来玩玩
android·java·kotlin
李少兄44 分钟前
解决IntelliJ IDEA 提交代码时无复选框问题
java·ide·intellij-idea
cyforkk1 小时前
Spring Boot @RestController 注解详解
java·spring boot·后端
叫我阿柒啊2 小时前
从Java全栈到前端框架:一次真实面试的深度复盘
java·spring boot·typescript·vue·database·testing·microservices
点云SLAM2 小时前
C++ 常见面试题汇总
java·开发语言·c++·算法·面试·内存管理
sniper_fandc2 小时前
IDEA修改系统缓存路径,防止C盘爆满
java·ide·intellij-idea
aristo_boyunv2 小时前
拦截器和过滤器(理论+实操)
java·数据仓库·hadoop·servlet
半夏陌离2 小时前
SQL 入门指南:排序与分页查询(ORDER BY 多字段排序、LIMIT 分页实战)
java·前端·数据库
CUIYD_19892 小时前
Eclipse 常用搜索功能汇总
java·ide·eclipse
野犬寒鸦3 小时前
力扣hot100:相交链表与反转链表详细思路讲解(160,206)
java·数据结构·后端·算法·leetcode