Java 8引入了 CompletableFuture ,一个可组合的Future的新实现(包括一堆thenXxx方法)。我想独占使用它,但我想使用的许多库只返回不可组合的 Future 实例。
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.
有没有办法在 CompleteableFuture 中包装一个返回的 Future 实例,以便我可以撰写它?
Is there a way to wrap up a returned Future instances inside of a CompleteableFuture so that I can compose it?
推荐答案有一种方法,但你不会喜欢它。以下方法将 Future< T> 转换为 CompletableFuture< T> :
There is a way, but you won't like it. The following method transforms a Future<T> into a CompletableFuture<T>:
public static <T> CompletableFuture<T> makeCompletableFuture(Future<T> future) { return CompletableFuture.supplyAsync(() -> { try { return future.get(); } catch (InterruptedException|ExecutionException e) { throw new RuntimeException(e); } }); }显然,这种方法的问题在于每个 Future的问题,一个线程将被阻止等待 Future 的结果 - 与期货的想法相矛盾。在某些情况下,可能会做得更好。但是,一般情况下,如果没有主动等待 Future 的结果,就没有解决方案。
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.
更多推荐
将Java Future转换为CompletableFuture
发布评论