Using the AsyncHttpClient
with Netty
provider will prevent the main program to terminate when we execute an asynchronous request.
For instance, the following program terminates after the println
, or not, depending on whether the provider is JDKAsyncHttpProvider
or NettyAsyncHttpProvider
:
public class Program {
public static CompletableFuture<Response> getDataAsync(String uri) {
final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
final CompletableFuture<Response> promise = new CompletableFuture<>();
asyncHttpClient
.prepareGet(uri)
.execute(new AsyncCompletionHandler<Response>(){
@Override
public Response onCompleted(Response resp) throws Exception {
promise.complete(resp);
asyncHttpClient.close(); // ??? Is this correct ????
return resp;
}
});
return promise;
}
public static void main(String [] args) throws Exception {
final String uri = "…";
System.out.println(getDataAsync(uri).get());
}
}
About the AsynHttpClient
the documentation states:
AHC is an abstraction layer that can work on top of the bare JDK, Netty and Grizzly. Note that the JDK implementation is very limited and you should REALLY use the other real providers.
To use AsyncHttpClient with Netty we just need to include the corresponding library in the java class path. So, we may run the previous Program
with one of the following class path configurations to use Netty, or not:
-cp .;async-http-client-1.9.24.jar;netty-3.10.3.Final.jar;slf4j-api-1.7.12.jar
will useNettyAsyncHttpProvider
-cp .;async-http-client-1.9.24.jar;slf4j-api-1.7.12.jar
will useJDKAsyncHttpProvider
What else should we do to use Netty provider correctly? For instance, I am closing the AsyncHttpClient
in AsyncCompletionHandler
. Is that correct?
Is there any configuration to change the observed behavior?