Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I start a CompletableFuture without blocking and do something when it's done?

The CompletableFuture API is fairly intimidating, lot's of accepts, and thens and other things; it's hard to tell why different options exist.

CompletableFuture<?> future = CompletableFuture.supplyAsync(() ->..., executor)

future.startNonBlocking...( (...) -> { callback behavior done when complete }

I'm basically trying to mimic a new Thread(() -> dostuff).start() but with better thread pooling, error handling, etc. Note: I don't actually need the Runnable interface here, I'm generifying a piece of existing code.

what's the right way to start my asynchronous task and execute behavior when it's complete? or handle an exception that is thrown?

like image 834
xenoterracide Avatar asked May 04 '16 04:05

xenoterracide


2 Answers

Here's a simple async callback:

CompletableFuture.supplyAsync(() -> [result]).thenAccept(result -> [action]);

Or if you need error handling:

CompletableFuture.supplyAsync(() -> [result]).whenComplete((result, exception) -> {
    if (exception != null) {
        // handle exception
    } else {
        // handle result
    }
});
like image 155
shmosel Avatar answered Oct 19 '22 10:10

shmosel


new Thread(() -> dostuff).start()

means that dostuff implements Runnable, so you may use

static CompletableFuture<Void> runAsync(Runnable runnable)    
static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)

also.

like image 2
Andrei_N Avatar answered Oct 19 '22 08:10

Andrei_N