3

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();   
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
DanglingPointer
  • 261
  • 1
  • 6
  • 19
  • 1
    Yes, it will wait until the `Future` completes. There is no benefit in `AsyncHttpClient` here. – Andy Turner Sep 02 '16 at 13:40
  • If you want to execute 2 or more requests at the same time, you can execute them concurrently and then wait for them to complete. That will only take as long as the longest-duration request, rather than the total time of all requests added together. – Erwin Bolwidt Sep 02 '16 at 13:43
  • If I have 1 async request made per main thread - then will each main thread remain blocked until async IO completes ? Does that mean - I can not get benefit of async client at all ? – DanglingPointer Sep 02 '16 at 13:48
  • How can you have multiple "main threads" ? You designate something "main" because it's the *main* one. Not sure what you mean with your comment. – Erwin Bolwidt Sep 02 '16 at 13:52
  • Apologies for confusion. By main thread, I meant the thread that is serving the original request. In my case, client calls system A, and System A acts like a proxy and sends request to system B using AsyncHttpClient – DanglingPointer Sep 02 '16 at 13:54

1 Answers1

7

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).

Brandon McKenzie
  • 1,655
  • 11
  • 26