通过同步方法调用创建CompletableFuture [英] Create CompletableFuture from a sync method call
问题描述
我想知道是否存在用于通过同步方法调用创建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) {
future.completeExceptionally(e);
}
future.complete(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 CompletableFuture.completedFuture("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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!