Avi Barel
Avi Barel

Reputation: 21

Retrofit 2 Uses too many threads

I am using Retrofit 2 in my Android application, and I have a lot of network calls. I ran into performance issues and after a long research, I saw that I have too many running threads in my app. I printed all the active threads in the app and saw a specific thread that had too many instances (several hundred) by the name of "OkHttp ConnectionPool" - I'm assuming it's connected to my retrofit calls.

Is there a way to prevent this thread from flooding the system?

Upvotes: 0

Views: 1414

Answers (2)

Culp
Culp

Reputation: 41

Can you post your code? Are you creating multiple instances of OkHttpClient? Each instance will bring along a new connection pool, so if you have a bunch of these in your application's lifecycle, it's going to get flooded.

You'll want to instantiate OkHttpClient as a singleton. See this comment in the OkHttp source code for more info.

If you need to modify the OkHttpClient to have a different configuration you can use the newBuilder() method, which will reuse the existing connection pool.

Upvotes: 1

imaadhrizni
imaadhrizni

Reputation: 438

IMHO in this kind of scenario it would be in your best interest to use a dependency injection framework alongside Retrofit. Like you said retrofit connections are quite expensive. I'm not an expert to give you much advice but it would really help if you looked at tutorials like this retrofit2 combined with dagger2. I've worked with retrofit and come across issues as you mention and this is because connection pool was not optimized. Just to give you an overview what dependency injection will do is simply let you keep a single instance of retrofit throughout your application and all you need to do is inject it wherever you need an instance. Dagger2 is what I've noted to be the best in doing the job so far you can check it out at Dagger By Google

You do have another option of using retrofit as a singleton. Once again please read on this as it's a useful design pattern. The singleton will also be easier in terms of implementing, for you but DI is going to help you on the long run in terms of app scope. For singleton take a look at this Stackoverflow.com answer

Once again please correct me if I'm wrong as I'm in the learning process as well :). Cheers

Upvotes: 1

Related Questions