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

相关推荐
black方块cxy几秒前
实现一个输入框多个ip以逗号分隔最多20组,且ip不能重复
java·服务器·前端
23.1 小时前
【Java】char字符类型的UTF-16编码解析
java·开发语言·面试
怒放吧德德1 小时前
Spring Boot实战:InfluxDB 2.x简单教程
java·spring boot·后端
indexsunny1 小时前
互联网大厂Java面试实战:核心技术与业务场景深度解析
java·spring boot·hibernate·security·microservices·interview
是小蟹呀^1 小时前
Java中的继承:从入门到精通
java·继承
bearpping1 小时前
怎么下载安装yarn
java
西门吹雪分身1 小时前
JDK8之四大核心函数式接口
java·函数式接口
华科易迅1 小时前
Spring AOP
java·后端·spring
架构师沉默1 小时前
Gemini 正式登陆香港,不用翻墙!
java·后端·架构
zihao_tom2 小时前
Spring WebFlux:响应式编程
java·后端·spring