Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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! 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;
    }
like image 217
Sergey Avatar asked Dec 19 '18 08:12

Sergey


1 Answers

because you are adding in parallel to a collection that is not thread safe, you could see missed entries, nulls 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.

like image 105
Eugene Avatar answered Oct 03 '22 05:10

Eugene