Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompletableFuture from ExecutorService

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 CompletableFutures.

In Guava, we have the ListeningExecutorService that returns ListenableFutures. Those ListenableFutures are, for my intents and purposes, as nice as CompletableFutures.

Still, I'd like to use Java's standard library as much as possible which means I'm looking for a way to get CompletableFutures from my custom executor.

like image 243
Matthias Braun Avatar asked Dec 11 '17 10:12

Matthias Braun


1 Answers

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.

like image 132
Matthias Braun Avatar answered Oct 20 '22 14:10

Matthias Braun