Using Java 8
great feature CompletableFuture, I'd like to transform my old async code using exceptions to this new feature. But the checked exception is something bothering me. Here is my code.
CompletableFuture<Void> asyncTaskCompletableFuture =
CompletableFuture.supplyAsync(t -> processor.process(taskParam));
The signature of process
method:
public void process(Message msg) throws MyException;
How do I deal with that checked exception in ComletableFuture?
The CompletableFuture.join() method is similar to the get method, but it throws an unchecked exception in case the Future does not complete normally.
It just provides a get() method which blocks until the result is available to the main thread. Ultimately, it restricts users from applying any further action on the result. You can create an asynchronous workflow with CompletableFuture. It allows chaining multiple APIs, sending ones to result to another.
runAsync. Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor after it runs the given action.
CompletableFuture provides three methods to handle them: handle() , whenComplete() , and exceptionally() .
I have tried this way, but I don't know whether it's a good way to solve the problem.
@FunctionalInterface
public interface RiskEngineFuncMessageProcessor<Void> extends Supplier<Void> {
@Override
default Void get() {
try {
return acceptThrows();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
Void acceptThrows() throws Exception;
With the FunctionalInterface of Supplier, I can wrap the exception:
final MyFuncProcessor<Void> func = () -> {
processor.process(taskParam);
return null;
};
CompletableFuture<Void> asyncTaskCompletableFuture =
CompletableFuture.supplyAsync(func)
.thenAccept(act -> {
finishTask();
})
.exceptionally(exp -> {
log.error("Failed to consume task", exp);
failTask( exp.getMessage());
return null;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With