xenoterracide
xenoterracide

Reputation: 16855

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?

Upvotes: 5

Views: 9386

Answers (2)

Andrei_N
Andrei_N

Reputation: 430

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.

Upvotes: 2

shmosel
shmosel

Reputation: 50716

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
    }
});

Upvotes: 2

Related Questions