简体   繁体   English

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

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

I've been doing some reading about CompletableFuture.我一直在阅读有关 CompletableFuture 的文章。

As of now I understand that CompletableFuture is different from Future in a sense that it provides means to chain futures together, to use callback to handle Future's result without actually blocking the code.到目前为止,我了解到 CompletableFuture 与 Future 不同,它提供了将 Future 链接在一起的方法,使用回调来处理 Future 的结果而不实际阻塞代码。

However, there is this complete() method that I'm having a hard time wrapping my head around.但是,我很难理解这个 complete() 方法。 I only know that it allows us to complete a future manually, but what is the usage for it?我只知道它可以让我们手动完成一个future,但是它有什么用呢? The most common examples I found for this method is when doing some async task, we can immediately return a string for example.我发现这种方法最常见的例子是在执行一些异步任务时,例如我们可以立即返回一个字符串。 But what is the point of doing so if the return value doesn't reflect the actual result?但是,如果返回值不能反映实际结果,那么这样做有什么意义呢? If we want to do something asynchronously why don't we just use regular future instead?如果我们想异步做一些事情,为什么不直接使用普通的未来呢? The only use I can think of is when we want to conditionally cancel an ongoing future.我能想到的唯一用途是当我们想要有条件地取消正在进行的未来时。 But I think I'm missing some important key points here.但我认为我在这里遗漏了一些重要的关键点。

complete() is equivalent to the function transforming the previous stage's result and returning getResponse("a1=Chittagong&a2=city") response, you can run this method in a different thread when getResponse() methods response available then thenApply() will be invoked to print log. complete() 相当于 function 转换前一阶段的结果并返回 getResponse("a1=Chittagong&a2=city") 响应,您可以在 getResponse() 方法响应可用时在不同的线程中运行此方法,然后调用 thenApply()打印日志。 no one will be blocked if you run getResponse(String url) in a different thread.如果您在不同的线程中运行 getResponse(String url),则不会阻止任何人。

This example shows a scenario where we are printing a log while getting responses from complete();此示例显示了我们在从 complete() 获取响应的同时打印日志的场景;

Code代码

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