xenoterracide xenoterracide - 2 years ago 97
Java Question

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


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
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download