Search code examples
javaspring-bootparallel-processingjava-streamjava-threads

Execute parallel method calls in java without aborting entire processing for any exception in a one or multiple method calls


I've a method

private void disableXYZ(Long rId, List<Long> disableIds, String requestedBy) {
        for (Long disableId : disableIds) {
            try {
                disablePackXYZ(UnSubscribeRequest.unsubscriptionRequest()
                        .requestedBy(requestedBy)
                        .cancellationReason("system")
                        .id(disableId)
                        .build());
            } catch (Exception e) {
                log.error("Failed to disable pack. id: {}, rId: {}. Error: {}", disableId, rId, e.getMessage());
            }
        }
    }

I want to make parallel method calls to disablePackXYZ with ids in disableIds list instead of an iterative for loop. But doing so I don't want to abort all the parallel calls if exception is thrown by any one or more disablePackXYZ calls. I can catch or suppress the exception but it should not abort processing of all the other threads or of the same thread for further tasks. Please suggest the approach for the same.

I went through java streams approach over the web -

final CompletableFuture<ParseException> thrownException = new CompletableFuture<>();
Stream.of(columns).parallel().forEach(column -> {
    try {
        result[column.index] = parseColumn(valueCache[column.index], column.type);
    } catch (ParseException e) {
        thrownException.complete(e);
    }});

For above approach, I found over web that if there is at least one exception thrown in a thread, the forEach invocation will propagate it (or one of them) to the caller. Hence, the current implementation doesn’t wait for the completion of all threads when it encounters an exception.


Solution

  • You've got a result[] array for storing results, just create an error[] array for storing exceptions. In your catch statement, store the exception into the error[] array and don't call thrownException.complete(e).