通过同步方法调用创建CompletableFuture

Sli*_*lim 1 java lambda asynchronous java-8 completable-future

我想知道是否存在一种从同步方法调用创建CompletableFuture的情况。如果没有,为什么?

长版:

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;
Run Code Online (Sandbox Code Playgroud)

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

final String parameters = "hello";
return CompletableFuture.superMethod(() -> {syncMethodCall(parameters)});
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 5

由于您接受了执行异步调用的答案,因此不清楚为什么首先要求“同步方法调用”。执行异步方法调用的任务非常简单CompletableFuture

String parameters="hello";
return CompletableFuture.supplyAsync(() -> syncMethodCall(parameters));
Run Code Online (Sandbox Code Playgroud)

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

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

handle该阶段之前join保证的情况下,syncMethodCall抛出一个异常,join不会,因为这似乎是你的意图。但是handle不会返回该阶段,而是将返回具有记录的异常的原始将来。
请注意,有一个技巧可以使用当前实现在调用者线程内完成所有操作:

return CompletableFuture.completedFuture("hello")
    .thenApply(parameters -> syncMethodCall(parameters));
Run Code Online (Sandbox Code Playgroud)

thenApply将来已经完成时,将立即评估传递给的函数。但是,抛出的异常仍syncMethodCall记录在返回的将来。因此,结果与您问题的“详细版本”相同。


Ale*_*dov 0

由于您希望您的 CompletableFuture 通过某个方法调用的结果完成,并且您不想自己完成该 CompletableFuture - 那么您不需要 CompletableFuture - 任何 Future 实现都可以。例如,

T function(parameters) {
  return new T();
}
T res1 = function(parameters); // sync call
Future<T> f = ForkJoinPool.commonPool.submit(() -> function(parameters));  // async call
T res2 =  f.get();
assert(res1.equals(res2));
Run Code Online (Sandbox Code Playgroud)