I have created a custom ExecutorService
ExecutorService executor =
new ThreadPoolExecutor(0, maxPoolSize, keepAliveTime, timeUnit,
new LinkedBlockingDeque<>());
to which I submit my tasks
Future<String> result = executor.submit(() -> "test");
As you can see, the executor returns a meager Future
; I'd much rather have a CompletableFuture
that I can chain with other CompletableFuture
s.
In Guava, we have the ListeningExecutorService
that returns ListenableFuture
s. Those ListenableFuture
s are, for my intents and purposes, as nice as CompletableFuture
s.
Still, I'd like to use Java's standard library as much as possible which means I'm looking for a way to get CompletableFuture
s from my custom executor.
In hindsight it's obvious: Don't try to get a CompletableFuture
from the executor, instead, pass the executor to the CompletableFuture
.
Like this:
CompletableFuture<String> futureOutput =
CompletableFuture.supplyAsync(() -> "test", executor);
The task will be executed using one of the threads provided by executor
and clients have all the conveniences of CompletableFuture
to get at the task's result.
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