将Java Future转换为CompletableFuture

编程入门 行业动态 更新时间:2024-10-26 18:25:32
本文介绍了将Java Future转换为CompletableFuture的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

本文发布于:2023-11-25 03:12:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628087.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   Java   Future   CompletableFuture

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!