繁体   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