我想知道是否存在用于从同步方法调用创建 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;
所需的简短版本(或种类):
final String parameters = "hello";
return CompletableFuture.superMethod(() -> {syncMethodCall(parameters)});
最佳答案
由于您接受了执行异步调用的答案,因此不清楚您为什么首先要求“同步方法调用”。使用 CompletableFuture
执行异步方法调用的任务非常简单:
String parameters="hello";
return CompletableFuture.supplyAsync(() -> syncMethodCall(parameters));
如果您的意图是强制 future 在返回时已经完成,则很容易强制执行:
String parameters="hello";
CompletableFuture<ReturnType> f = CompletableFuture.supplyAsync(
() -> syncMethodCall(parameters));
f.handle((x,y) -> null).join();
return f;
join
之前的handle
阶段确保在 syncMethodCall
抛出异常的情况下,join
不会,因为这似乎是你的意图。但是 handle
阶段不会返回,而是返回带有记录异常的原始 future。
请注意,有一个技巧可以在当前实现的调用者线程中执行所有操作:
return CompletableFuture.completedFuture("hello")
.thenApply(parameters -> syncMethodCall(parameters));
传递给 thenApply
的函数将在 future 已经完成时立即求值。但是,syncMethodCall
抛出的异常仍然会记录在返回的 future 中。所以结果与您问题的“长版”相同。
关于java - 从同步方法调用创建 CompletableFuture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37863100/