Anurator
Anurator

Reputation: 115

Completable Future with Executor for handling Exceptions only

There is a list of objects List<Foo> fooDetails, which I will use to create Bar request corresponding to each element of fooDetails from database and then do a rest template call.

public void startProcess(List<Foo> fooDetails) throws Exception {

List<CompletableFuture<String>> futures = fooDetails.stream()
                .map(this::processFoo)
                .collect(Collectors.toList());

        List<String> failedFooPushList = futures.stream()
                .map(future -> {
                    try {
                        return future.get();  // Returns null if successful for that store
                    } catch (Exception e) {
                        return null;
                    }
                })
                .filter(Objects::nonNull)  // Filter failed (non-null) results
                .collect(Collectors.toList());

        if (!failedFooPushList.isEmpty()) {
            throw new SyncException("Foo failed for foo details: {}" + failedFooPushList);
        }
    }

    private CompletableFuture<String> processFoo(Foo fooDetail) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Bar request = barService.createBarFromDB(
                        Collections.singletonList(foodetail));

                boolean barPushFailed = booleanResponseClient.updateBar(request);

                if (barPushFailed) {
                    return fooDetail.getName();
                }

                return null;  // Return null to indicate success
            } catch (Exception ex) {
                return fooDetail.getName();
            }
        });
    }

The list can be very large and I suppose I should use ExecutorService with it. I am new to Java and need to know How to get the list of all the names of from the List<Foo> fooDetails which threw exception in a thread-safe manner?

Upvotes: 0

Views: 45

Answers (0)

Related Questions