Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checked exception with CompletableFuture [duplicate]

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?

like image 443
Yolanda Avatar asked Sep 06 '16 03:09

Yolanda


People also ask

Can CompletableFuture throw exception?

The CompletableFuture.join() method is similar to the get method, but it throws an unchecked exception in case the Future does not complete normally.

Is Completable future get blocking?

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.

What does CompletableFuture runAsync do?

runAsync. Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor after it runs the given action.

How do you handle Completable futures?

CompletableFuture provides three methods to handle them: handle() , whenComplete() , and exceptionally() .


1 Answers

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;
                        });
like image 73
Yolanda Avatar answered Oct 18 '22 19:10

Yolanda