Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit2 - OkHttp ConnectionPool threads grows to 100+ threads. Why?

I am using retrofit2 on a java service to connect to a REST API and fetch data.

The code looks like this:

Retrofit retrofit =
        new Retrofit.Builder().baseUrl(endPoint).addConverterFactory(JacksonConverterFactory.create())
                              .build();

SyncCentralLojaProxySvc svc = retrofit.create(SyncCentralLojaProxySvc.class);

LogVerCentralLojaEntity entity = syncSvc.getLogVerByCdFilial(filial);
long cd_log = (entity != null) ? entity.getCdLog() : 0;

Call<LogCentralLojaCompactoCollectionDto> call = svc.getLogCompacto(filial, cd_log);

Response<LogCentralLojaCompactoCollectionDto> response = call.execute();

//NOT_MODIFIED
if (response.code() == 304) {
    return 0;
}

if (!response.isSuccessful())
    throw new IOException(response.errorBody().string());

LogCentralLojaCompactoCollectionDto body = response.body();

Its a simple data fetch that runs synchronously (not in parallel) every few seconds.

I noticed throught VisualVM that the OkHttp thredas grows too much. The app would never user 100 operations in parallel. In fact, it only needs one.

How do I tune this? Is it natural to have so many threads?

VisualVM Thread Monitor

like image 558
Thiago Sayão Avatar asked Jul 28 '17 13:07

Thiago Sayão


People also ask

Which is better OkHttp or retrofit?

Retrofit is basically architecture above the OKHTTP, it internally uses OkHttp to make any request , earlier in jave if we want to make any request we have HTTPUrl connection or HTTPS Url connect know retrofit okHttp handles everything ( it divides into packages it marks headers )for us if we need to send some ...

What is connection pool in OkHttp?

[jvm]\ class ConnectionPool. Manages reuse of HTTP and HTTP/2 connections for reduced network latency. HTTP requests that share the same Address may share a Connection. This class implements the policy of which connections to keep open for future use.

How do I add OkHttp to retrofit?

Solution 1: Sharing Default OkHttp Instance In order to make them share a single OkHttp instance, you can simply pass it explicitly on the builder: OkHttpClient okHttpClient = new OkHttpClient(); Retrofit retrofitApiV1 = new Retrofit. Builder() . baseUrl("https://futurestud.io/v1/") .


1 Answers

Setting a global client with the connection pool configuration solved the issue:

ConnectionPool pool = new ConnectionPool(5, 10000, TimeUnit.MILLISECONDS);

OkHttpClient client = new OkHttpClient.Builder()
                              .connectionPool(pool)
                              .build();

Retrofit retrofit =
        new Retrofit.Builder().baseUrl(endPoint)
                              .client(client)
                              .addConverterFactory(JacksonConverterFactory.create())
                              .build();
like image 92
Thiago Sayão Avatar answered Sep 26 '22 11:09

Thiago Sayão