Java 8 introduces CompletableFuture
, a new implementation of Future that is composable (includes a bunch of thenXxx methods). I'd like to use this exclusively, but many of the libraries I want to use return only non-composable Future
instances.
Is there a way to wrap up a returned Future
instances inside of a CompleteableFuture
so that I can compose it?
Suggestion:
http://www.thedevpiece.com/converting-old-java-future-to-completablefuture/
But, basically:
And, the CompletablePromise:
Example:
There is a way, but you won't like it. The following method transforms a
Future<T>
into aCompletableFuture<T>
:Obviously, the problem with this approach is, that for each Future, a thread will be blocked to wait for the result of the Future--contradicting the idea of futures. In some cases, it might be possible to do better. However, in general, there is no solution without actively wait for the result of the Future.
If the library you want to use also offers a callback style method in addition to the Future style, you can provide it a handler that completes the CompletableFuture without any extra thread blocking. Like so:
Without the callback the only other way I see solving this is to use a polling loop that puts all your
Future.isDone()
checks on a single thread and then invoking complete whenever a Future is gettable.Let me suggest another (hopefully, better) option: https://github.com/vsilaev/java-async-await/tree/master/com.farata.lang.async.examples/src/main/java/com/farata/concurrent
Briefly, the idea is the following:
CompletableTask<V>
interface -- the union of theCompletionStage<V>
+RunnableFuture<V>
ExecutorService
to returnCompletableTask
fromsubmit(...)
methods (instead ofFuture<V>
)Implementation uses an alternative CompletionStage implementation (pay attention, CompletionStage rather than CompletableFuture):
Usage:
I published a little futurity project that tries to make better than the straightforward way in the answer.
The main idea is to use the only one thread (and of course with not just a spin loop) to check all Futures states inside, which helps to avoid blocking a thread from a pool for each Future -> CompletableFuture transformation.
Usage example: