为什么流无法在并行模式下工作?

huangapple go评论165阅读模式
英文:

Why the stream doesn't work in parallel mode?

问题

我有一段代码:

rows = types.stream().parallel().map(s -> {
    switch (s){
        case NDBaseDocumentModel.DOC_TYPE_NSS:
            return getDocsOfSpecificTypeAndCountItsDupes(NDGostStandardsModel.TYPE_ND_GOST_STANDARDS, null,systemMessages.getString("form20.nss.name")).values();
        case NDBaseDocumentModel.DOC_INT_REG_STANDARDS:
            return getDocsOfSpecificTypeAndCountItsDupes(NDIntRegStandardsModel.TYPE_ND_INT_REG_STANDARDS, null,systemMessages.getString("form20.int_reg")).values();
    }
    return new HashSet<Form20Row>();
}).flatMap(o -> {
    return o.stream();
}).collect(Collectors.toList());

而且它不起作用返回零行),但是当我移除 "parallel()" 调用时可以正常工作相同数据上的 14 行)。有人可以告诉我为什么吗拜托
拜托


<details>
<summary>英文:</summary>

I have a code :

    rows = types.stream().parallel().map(s -&gt; {
        switch (s){
            case NDBaseDocumentModel.DOC_TYPE_NSS:
                return getDocsOfSpecificTypeAndCountItsDupes(NDGostStandardsModel.TYPE_ND_GOST_STANDARDS, null,systemMessages.getString(&quot;form20.nss.name&quot;)).values();
            case NDBaseDocumentModel.DOC_INT_REG_STANDARDS:
                return getDocsOfSpecificTypeAndCountItsDupes(NDIntRegStandardsModel.TYPE_ND_INT_REG_STANDARDS, null,systemMessages.getString(&quot;form20.int_reg&quot;)).values();
        }
        return new HashSet&lt;Form20Row&gt;();
    }).flatMap(o -&gt; {
        return o.stream();
    }).collect(Collectors.toList());

And it doesn&#39;t work (return zero rows), but work fine when I remove &quot;parallel()&quot; call (14 rows on same data). Could somebody tell me why, please??
Please?

</details>


# 答案1
**得分**: 1

并行流程使用线程池进行处理因此您的方法`getDocsOfSpecificTypeAndCountItsDupes`需要是线程安全的

如果移除`parallel()`并在同一线程上处理可以解决您的问题因此似乎该方法中有一些不是线程安全的内容这可能是您的问题

<details>
<summary>英文:</summary>

Parallel streams are processed using a thread pool, and as such your method `getDocsOfSpecificTypeAndCountItsDupes` needs to be thread-safe.

As removing the `parallel()` and processing it on the same thread fixes your issue, it seems likely that there&#39;s something in the method that isn&#39;t thread-safe, which will be your problem.

</details>



huangapple
  • 本文由 发表于 2020年8月26日 05:03:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63587074.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定