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?
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
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With