Skip to content
标签
欢迎扫码关注公众号

并行流处理 (parallelStream) forEach 的重复问题

最近使用 parallelStream 方法在处理一些批量调用 http 接口时,发现了部分列表项重复执行了。

示例代码如下:

java
aList.parallelStream()
        .forEach(item -> {
            // do something
        });

本以为是数据源的问题,但查看打印的日志后发现数据源并没有问题,这才想到是不是并行流处理导致的问题。
这篇博客中介绍的比较详细,其原因是数据源 List<T> 并不是线程安全的,导致多线程在竞争获取列表项时出现了重复。

解决方案是使用 Collections 提供的一系列 synchronized 开头的静态方法,将其转化为线程安全的对应类型。

java
Collections.synchronizedList(aList).parallelStream()
        .forEach(item -> {
            // do something
        });

参考

  1. parallel 循环 java_使用 Java8 新特性 parallelStream 遇到的坑
  2. 使用 parallelStream 进行遍历的坑,以及如何进行避免异步操作中出现的问题

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.