簡體   English   中英

CompletableFuture: anyOne 調用了哪個方法,我怎樣才能得到想要的值

[英]CompletableFuture: anyOne which method is called and how can I get the desirable value

我需要異步調用一個帶有不同輸入參數(比如id)的方法,該方法返回true或false,而false output是不可取的,所以我應該等待一個true output。一旦我得到一個true,我不關心其他電話,我只需要知道真正的 output 對應於哪個輸入(id)。

我調用這段代碼,我應該如何知道responded方法的input id呢? 它可能有一個更完整的未來。 下一個問題是萬一得到假,我怎么能跳過並等待得到真,因為我需要從 myService.myMethod(int input) 之一接收到真?

CompletableFuture<Boolean> completableFuture= CompletableFuture.supplyAsync(() -> myService.myMethod(1));
CompletableFuture<Boolean> completableFuture2= CompletableFuture.supplyAsync(() -> myService.myMethod(2));
CompletableFuture<Boolean> completableFuture3= CompletableFuture.supplyAsync(() -> myService.myMethod(3));
CompletableFuture<Boolean> completableFuture4= CompletableFuture.supplyAsync(() -> myService.myMethod(4));

CompletableFuture<Object> result =
        CompletableFuture.anyOf(completableFuture, completableFuture2,completableFuture3,,completableFuture4).thenApply(s -> s);

每個結果都可能是錯誤的這一事實使這有點棘手,因為你不能過早中止。 以下應該有效; 它允許每個CompletableFuture將其結果發布到隊列,以及一個指示所有工作已完成的標記值。 然后從成功的隊列中取出第一個元素; 如果沒有,如果您讀取哨兵值,您就會知道所有結果都是錯誤的。

record Result (int id, boolean value) {}
final Result sentinel = new Result(Integer.MIN_VALUE, false);

// one more than the number of results, for the sentinel
BlockingDeque<Result> results = new LinkedBlockingDeque<>(5);
// the number of results exactly
CountDownLatch latch = new CountDownLatch(4);

CompletableFuture.runAsync(() -> {
    Record record = new Record(1, myService.myMethod(1));
    results.add(record);
    latch.countDown();
});
// etc for 2-4
CompletableFuture.runAsync(() -> {
    try {
        latch.await();
    } catch (InterruptedException e) {
        // log or something?
    } finally {
        results.add(sentinel);
    }
});

Result result = results.take();
while (!result.value() && !result.equals(sentinel)) {
    result = results.take();
}

哨兵僅在每個結果發布后添加(由於CountDownLatch ),確保它始終是最后一個元素。

當循環結束時,如果result.equals(sentinel) ,所有結果都是假的。 否則, result包含第一個可用的成功結果的 ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM