处理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 分钟前
12.Java的异常
java·开发语言
装不满的克莱因瓶13 分钟前
Java7新特性:try-with-resources写法
java·前端·javascript·jdk·新特性·jdk7
前路不黑暗@29 分钟前
Java项目:Java脚手架项目的通用组件的封装(六)
java·开发语言·spring
chilavert3181 小时前
技术演进中的开发沉思-368:锁机制(中)
java·开发语言·jvm
~央千澈~2 小时前
抖音弹幕游戏开发之第12集:添加冷却时间机制·优雅草云桧·卓伊凡
java·服务器·前端
HAPPY酷2 小时前
C++ 多线程实战三板斧
java·开发语言·c++·技术美术
独自破碎E2 小时前
BISHI54货物堆放
android·java·开发语言
json{shen:"jing"}2 小时前
分割回文串
java
workflower3 小时前
易用性和人性化需求
java·python·测试用例·需求分析·big data·软件需求
小灵不想卷3 小时前
LangChain4 初体验
java·langchain·langchain4j