我是 Java 新手,正在研究 Springboot POSTING 以休息端點。我有一個使用 CompletableFuture 的場景,想知道如何鏈接多個期貨。我也不需要任何結果傳遞給期貨。
場景 => Future f1 成功,然后 Future f2。如果 (f1 和 f2 ) 成功,則 Future f3 ;(f1 或 f2 ) 失敗然后 f3
我目前正在使用 supplyAsync,這是正確的方法嗎?
CompletableFuture<String> f1 = CompletableFuture.supplyAsync( () -> postToEndpointA(a) ).thenCompose( () -> postToEnpointB(b))
我現在應該如何鏈接 f3?
uj5u.com熱心網友回復:
CompletableFutures 可以鏈接以處理成功的運行以及失敗的運行。
支持您的用例的結構之一如下所示:
public class Test {
public static void main(String[] args) throws JsonProcessingException, InterruptedException {
CompletableFuture.runAsync(() -> f1(false)) // f1 takes a bool val to switch success and fail runs
// f2 will run only if f1 completed successfully
.thenRun(Test::f2)
// throwable can be examined to check if there was any exception
// at previous stages. If throwable == null, there was no error
.whenComplete((unused, throwable) -> {
handleError(throwable);
f3();
});
// Wait for the thread above to complete
ForkJoinPool.commonPool().awaitTermination(4, TimeUnit.SECONDS);
}
private static void f1(boolean shouldFail) {
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
if (shouldFail)
throw new RuntimeException("F1: Failed..");
System.out.println("f1: Completed.. ");
}
private static void f2() {
System.out.println("f2: Started...");
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
System.out.println("f2: Completed..");
}
private static void f3() {
System.out.println("f3: Runs irrespective of f1 and f2 result");
}
private static void handleError(Throwable throwable) {
if (throwable != null)
System.out.println(throwable.getMessage());
}
}
輸出
shouldFail: false
f1: Completed..
f2: Started...
f2: Completed..
f3: Runs irrespective of f1 and f2 result
shouldFail: true
java.lang.RuntimeException: F1: Failed..
f3: Runs irrespective of f1 and f2 result
uj5u.com熱心網友回復:
CompletableFutures 可以通過呼叫thenRun運行一個獨立于結果的任務來鏈接,或者thenAccept它接受初始結果的呼叫,supplyAsync并呼叫你傳遞給thenAccept方法的函式
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/350220.html
上一篇:更改HTML檔案圖示
