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?
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 ...
[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.
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/") .
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With