FrancMo
FrancMo

Reputation: 2709

Java asyncHttpClient new thread for each connection

Im doing library in java, library is for calling external service API. For this I am using AsyncHttpClient

Some part of code:

 public CompletableFuture<Optional<TokensResponse>> clientCredentialsGrant(String clientId, String clientSecret, String deviceId, Optional<String> scope) {
        AsyncHttpClient asyncHttpClient = asyncHttpClient();
        BoundRequestBuilder requestBuilder = asyncHttpClient
                .preparePost(host + "/oauth2/token")
                .addFormParam("grant_type", "client_credentials")
                .addFormParam("device_id", deviceId)
                .addFormParam("client_id", clientId)
                .addFormParam("client_secret", clientSecret);

        if (scope.isPresent()) {
            requestBuilder.addFormParam("scope", scope.get());
        }

        return runRequestWithTokenResponse(requestBuilder, asyncHttpClient);
    }

and if some project which is using this lib I will run for example 1000 requests even if they will finish I end up with a lot of threads hanged. After reach request I am doing:

asyncHttpClient.close();

Can I define some thread pool to be used ?

Typically, AHC will usually underperform if you create a new client for each request, as it will create new threads and connection pools for each

This is what I am actually doing..

Upvotes: 0

Views: 1964

Answers (2)

Mike Mike
Mike Mike

Reputation: 608

You do not need to define a thread pool. AHC takes care of concurrent execution. Just create one AHC instance and use it everywhere. For example, make this a class field:

AsyncHttpClient asyncHttpClient = asyncHttpClient();

Under the hood AHC has two types of threads:

  1. For I/O operation. On your screen, it's AsyncHttpClient-x-x threads. AHC creates 2*core_number of those.
  2. For timeouts. On your screen, it's AsyncHttpClient-timer-1-1 thread. Should be only one.

Any different number means you’re creating multiple clients. It's redundant in your case.

Upvotes: 0

Ivalberto
Ivalberto

Reputation: 433

when you initialize the object AsyncHttpClient

you can do this , connection pool behaviour can be configured via AsyncHttpClientConfig:

AsyncHttpClient http = asyncHttpClient(config()
    .setMaxConnections(500)
    .setMaxConnectionsPerHost(200)
    .setPooledConnectionIdleTimeout(100)
    .setConnectionTtl(500)
);

Upvotes: 3

Related Questions