Reputation: 1
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?
Upvotes: 0
Views: 602
Reputation: 1652
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
Upvotes: 1