简体   繁体   中英

What is the purpose of CompletableFuture's complete method?

I've been doing some reading about 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.

However, there is this complete() method that I'm having a hard time wrapping my head around. I only know that it allows us to complete a future manually, but what is the usage for it? 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. no one will be blocked if you run getResponse(String url) in a different thread.

This example shows a scenario where we are printing a log while getting responses from 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM