簡體   English   中英

CompletableFuture 的完整方法的目的是什么?

[英]What is the purpose of CompletableFuture's complete method?

我一直在閱讀有關 CompletableFuture 的文章。

到目前為止,我了解到 CompletableFuture 與 Future 不同,它提供了將 Future 鏈接在一起的方法,使用回調來處理 Future 的結果而不實際阻塞代碼。

但是,我很難理解這個 complete() 方法。 我只知道它可以讓我們手動完成一個future,但是它有什么用呢? 我發現這種方法最常見的例子是在執行一些異步任務時,例如我們可以立即返回一個字符串。 但是,如果返回值不能反映實際結果,那么這樣做有什么意義呢? 如果我們想異步做一些事情,為什么不直接使用普通的未來呢? 我能想到的唯一用途是當我們想要有條件地取消正在進行的未來時。 但我認為我在這里遺漏了一些重要的關鍵點。

complete() 相當於 function 轉換前一階段的結果並返回 getResponse("a1=Chittagong&a2=city") 響應,您可以在 getResponse() 方法響應可用時在不同的線程中運行此方法,然后調用 thenApply()打印日志。 如果您在不同的線程中運行 getResponse(String url),則不會阻止任何人。

此示例顯示了我們在從 complete() 獲取響應的同時打印日志的場景;

代碼

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CompletableFutureEx {

    Logger logger = Logger.getLogger(CompletableFutureEx.class.getName());

    public static void main(String[] args) {
        new CompletableFutureEx().completableFutureEx();
    }

    private void completableFutureEx() {
        var completableFuture = new CompletableFuture<String>();
        completableFuture.thenApply(response -> {
            logger.log(Level.INFO, "Response : " + response);
            return response;
        });
        
        //some long process response
        try {
            completableFuture.complete(getResponse("a1=Chittagong&a2=city"));
        } catch (Exception e) {
            completableFuture.completeExceptionally(e);
        }

        try {
            System.out.println(completableFuture.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    private String getResponse(String url) throws URISyntaxException, IOException, InterruptedException {
        var finalUrl = "http://localhost:8081/api/v1/product/add?" + url;
        //http://localhost:8081/api/v1/product/add?a1=Chittagong&a2=city
        var request = HttpRequest.newBuilder()
                .uri(new URI(finalUrl)).GET().build();
        var response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("response body " + response.body());
        return response.body();
    }
}

暫無
暫無

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

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