通过同步方法调用创建CompletableFuture

编程入门 行业动态 更新时间:2024-10-23 04:48:16
本文介绍了通过同步方法调用创建CompletableFuture的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道是否存在用于通过同步方法调用创建CompletableFuture的单行代码.如果没有,为什么?

I would like to know if a one-liner exists for creating a CompletableFuture from a synchron method call. If no, why?

长版:

final CompletableFuture<ReturnType> future = new CompletableFuture<>(); final String parameters = "hello"; ReturnType result; try { result = syncMethodCall(parameters); } catch (Exception e) { futurepleteExceptionally(e); } futureplete(result); return future;

所需的简短版本(或同类):

Short desired version (or kind):

final String parameters = "hello"; return CompletableFuture.superMethod(() -> {syncMethodCall(parameters)});

推荐答案

由于您接受了执行异步调用的答案,因此尚不清楚为什么首先要求同步方法调用".使用CompletableFuture:

Since you accepted an answer that performs an asynchronous call, it’s unclear why you asked for a "synchron method call" in the first place. The task of performing an asynchronous method invocation is quite easy with CompletableFuture:

String parameters="hello"; return CompletableFuture.supplyAsync(() -> syncMethodCall(parameters));

如果您打算强制将来在返回时已经完成,那么执行起来很容易:

If your intention was to enforce the future to be already completed upon returning, it’s easy to enforce:

String parameters="hello"; CompletableFuture<ReturnType> f = CompletableFuture.supplyAsync( () -> syncMethodCall(parameters)); f.handle((x,y) -> null).join(); return f;

join之前的handle阶段可确保在syncMethodCall引发异常的情况下,join不会出现异常,因为这似乎是您的意图.但是不会返回handle阶段,而是将返回具有记录的异常的原始将来. 请注意,使用当前的实现方法可以在调用者的线程中完成所有操作:

The handle stage before the join ensures that in case syncMethodCall threw an exception, join won’t, as that seems to be your intention. But the handle stage is not returned, instead, the original future with the recorded exception will be returned. Note that there’s a trick to do everything within the caller’s thread with the current implementation:

return CompletableFuturepletedFuture("hello") .thenApply(parameters -> syncMethodCall(parameters));

将来已经完成时,传递给thenApply的函数将立即进行评估.但是,syncMethodCall引发的异常仍记录在返回的Future中.因此,结果与您问题的详细版本"相同.

The function passed to thenApply will be evaluated immediately when the future is already completed. But still, exceptions thrown by syncMethodCall are recorded in the returned future. So the outcome is identical to the "long version" of your question.

更多推荐

通过同步方法调用创建CompletableFuture

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

发布评论

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

>www.elefans.com

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