Multiple threads in an Android activity / service

I have an Android app where in the list view for each item in the list I upload an image from the network to a separate stream. Therefore, if 8 items are displayed in the list view, the activity will try to start 8 different threads, one for each item in the list, to load the image. When you scroll down the list, the number of threads may increase if previous threads have not completed execution.

I am curious to know how many simultaneous threads can one Android app run in parallel? Is there a limit? I would not expect these streams to trigger ANR over a slow internet connection, since they are independent? But it seems that ANR is really happening, and maybe because the application / device is running on resources, so it takes more than 5 seconds to create a new activity in the user interface, which leads to ANR?

Any tips on how I can make responsiveness better with a slow internet connection will be appreciated.

+4
source share
2 answers

One way to handle this is to use a thread pool. I do not know if there is a finite limit to the number of simultaneous threads, but creating and destroying them is expensive. With a thread pool, you have a limited number of threads that can perform tasks.

A thread can be reused after a task completes, resulting in improved performance.

If you have more work to be done at the same time than you have threads to do it, you need to queue the work until the thread is free.

+5
source

Later, I found out that my application was freezing and slowing down not because there were too many threads generated by it. But this was due to the fact that I used the Service, not the IntentService. And my IO network happened in the main thread in the Service. This means that a blocking IO will suppress the main thread, and the phone / application will tend to die and display ANR.

Subsequently, I changed my project to run network I / O operations on spawned threads in my services that brought life back to the application. Everything was smoother as expected.

Thus, whenever your services lead to ANR, make sure that if you do not use IntentService (they run tasks in separate threads), then you perform blocking operations on new threads.

Hope this helps someone.

+6
source

All Articles