I have the following code and it behaves non deterministically sometimes. For example I pass 3 events there and the output have only two! 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. 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. Also bare in mind, that parallel
!= faster
in like 99% of the cases, you need to measure this, but I doubt you need it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With