javajava-8java-stream

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;
    }

Solution

  • 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.