Exception propagation in CompletableFuture (java)

Tags: , ,



How can I propagate exception encountered in the following code inside CompletableFuture.runAsync to my main thread? I want to catch the IllegalStateException in my main thread.

CompletableFuture.runAsync(() -> {
        // some business logic which needs to run indefinitely
}).exceptionally(ex -> {
    // ex.printStackTrace();
    throw new IllegalStateException("Failed to process", ex);
});

Answer

One option would be to create a Collection of Throwable objects and when the CompletableFuture completes you can add the exception to the Collection (if it’s not null). Then on your main thread you could poll that Collection.

        Set<Throwable> exception = new CopyOnWriteArraySet<>();

        CompletableFuture.runAsync(() -> {

        }).whenComplete((method, e) -> exception.add(e));

Another option is to use whenComplete with ExecutorService. This may not work if you’re not using an ExecutorService. The idea is that whenComplete will return on the mainThread ExecutorService.

        ExecutorService mainThread = Executors.newSingleThreadExecutor();
        
        CompletableFuture.runAsync(() -> {

        }).whenCompleteAsync((method, throwable) -> {
            // throw or handle in some way on main thread
        }, mainThread);


Source: stackoverflow