Ser*_*gey 4 java java-8 java-stream
我有以下代码,有时行为不确定.例如,我在那里传递3个事件,输出只有两个!你能解释一下这种行为的原因吗?
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;
}
Run Code Online (Sandbox Code Playgroud)
因为你要并行添加一个非线程安全的集合,你可以null在输出列表中看到错过的条目- 真的不知道会发生什么.而是修复你的代码:
return events.parallelStream()
.map(this::getEventResponse)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
map应该没有任何副作用,你的map操作显然是这样,这是文档禁止的.还要记住,那个parallel!= faster在99%的情况下,你需要测量它,但我怀疑你需要它.
| 归档时间: |
|
| 查看次数: |
178 次 |
| 最近记录: |