Search code examples
springjava-8completable-future

Does a CompletableFuture completes on a re-thrown exception?


I've just started using CompletableFuture and already loving it.

But one strange thing that appears to me while using a CompletableFuture is its method called "exceptionally"

Let's say I've a CompletableFuture<?> cf1.

Now, once the data arrives, my code is applying some processing logic. In case of an exception, I make use of exceptionally method to rethrow MyCustomException

cf1  
.thenApply(myData->Some Processing Logic)  
.exceptionally(ex-> throw new MyCustomException())

cf.get(); 

Interestingly, the call to get method hangs indefinitely until I terminate the program. Does that mean that if a CompletableFuture re-throws an exception from the exceptionally block, the future will not be marked as complete? Do I need to explicity mark it as complete?


Solution

  • From docs the get method throws exception if the future completed exceptionally

    ExecutionException - if this future completed exceptionally

    So either you can return some value from exceptionally to identify the exception is thrown during thenApply and call get method for value

    Second way, before calling get method you can make that future object completed using allOf, and check if the future is completed exceptionally

    CompletableFuture.allOf(completableFuture);
    completableFuture.isCompletedExceptionally();  //true