英文:
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 -> {
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());
And it doesn't work (return zero rows), but work fine when I remove "parallel()" 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's something in the method that isn't thread-safe, which will be your problem.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论