Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get() immediately after obtaining ListenableFuture

If I get a ListenableFuture<X> when calling an external system using the AsyncHttpClient, and I call get() immediately - will the current thread not wait until the async thread is ready with a Response? If that is true, what is the benefit of using AsyncHttpClient?

AsyncHttpClient httpClient = new AsyncHttpClient();
ListenableFuture<Response> futureResponse = httpClient.execute(url, payload, headers);

// If this is immediately on next line, am I getting any benefit?
Response response = futureResponse.get();   
like image 632
DanglingPointer Avatar asked Sep 07 '26 13:09

DanglingPointer


1 Answers

Per the Future interface contract, which ListenableFuture implements, get() returns the result of the Future, and thusly must block until necessary computations are complete.

Executing get() immediately after a Future call would give you no benefit, if system A calls system B with an async request, calling get right after will cause system A to wait.

If you want system A to keep doing things while B is processing the request, you may wish to add a Callback or Listener to the ListenableFuture so that A can do what it needs to do when B comes back (the ability to do this is kind of the reason why ListenableFuture exists, as a matter of fact).

like image 157
Brandon McKenzie Avatar answered Sep 10 '26 01:09

Brandon McKenzie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!