简体   繁体   中英

CompletableFuture thenAccept does not work

Welcome, I am so confused why this part of code does not work.

public class Main {
public static void main(String[] args) throws URISyntaxException {
    final String URL = "https://jsonplaceholder.typicode.com/users/1";

    HttpRequest request = HttpRequest.newBuilder(new URI(URL)).GET().timeout(Duration.of(10, ChronoUnit.SECONDS)).build();

    HttpClient.newHttpClient().sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenAcceptAsync(r -> {
        System.out.println(r.statusCode());
        System.out.println(Thread.currentThread().getName());
    }, Executors.newFixedThreadPool(10));

    
    System.out.println("END OF PROGRAM");
}

}

And the result is:

END OF PROGRAM

If i have provided ExecutorService JVM should wait for CompletableFuture was completed (.thenAceptAsync section) but the program was finishing immediately.

Probably my mindset is wrong. Could somebody explain me this?

The program exits before the request is completed. The request is executed asynchronously using sendAsync and therefore it does not block the execution of the program.

To block the execution and wait for the API response, you must use response.get(); as follows:

public static void main(String[] args) throws URISyntaxException, ExecutionException,
     InterruptedException {
final String URL = "https://jsonplaceholder.typicode.com/users/1";
    
HttpRequest request = HttpRequest.newBuilder(new URI(URL)).GET().timeout(Duration.of(10, ChronoUnit.SECONDS)).build();
    
CompletableFuture<Void> response = HttpClient.newHttpClient()
                    .sendAsync(request, HttpResponse.BodyHandlers.ofString())
                    .thenAcceptAsync(r -> {
                System.out.println(r.statusCode());
                System.out.println(Thread.currentThread().getName());
}, Executors.newFixedThreadPool(10));
    
 response.get();//wait for API response
 System.out.println("END OF PROGRAM");
}

Output:

200
pool-1-thread-1
END OF PROGRAM

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