简体   繁体   English

Java parallelStream映射错过了记录

[英]Java parallelStream map misses records

I have the following code and it behaves non deterministically sometimes. 我有以下代码,有时行为不确定。 For example I pass 3 events there and the output have only two! 例如,我在那里传递3个事件,输出只有两个! Could you explain the reason of such behaviour? 你能解释一下这种行为的原因吗?

public List<AbstractTransactionResponse> getEventResponse(final List<AbstractEvent> events){

        List<AbstractTransactionResponse> abstractTransactionResponses = new ArrayList<>();
        events.parallelStream().map(event -> {
            abstractTransactionResponses.add(getEventResponse(event));
            return null;
        }).collect(Collectors.toList());
        return abstractTransactionResponses;
    }

because you are adding in parallel to a collection that is not thread safe, you could see missed entries, null s in your output list - it is really unknown what will happen. 因为你要并行添加一个非线程安全的集合,你可以在输出列表中看到错过的条目, null s - 真的不知道会发生什么。 Instead fix your code: 而是修复你的代码:

return events.parallelStream()
             .map(this::getEventResponse)
             .collect(Collectors.toList());

map is supposed to not have any side-effects and your map operation obviously does, this is something the documentation prohibits. map应该没有任何副作用,你的map操作显然也有,这是文档禁止的。 Also bare in mind, that parallel != faster in like 99% of the cases, you need to measure this, but I doubt you need it. 还要记住, parallel != 99%的情况下faster ,你需要测量这个,但我怀疑你需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM