CompletableFuture from ExecutorService

Matthias Braun :

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.

Matthias Braun :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466273&siteId=1