xenoterracide xenoterracide - 7 months ago 34
Java Question

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?

Answer

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