Take the 2-minute tour ×

I have a fragment that fetches some data from a database, using a AsyncTaskLoader, which the fragment will then display. The fragments are presented in a ViewAnimator, and the user can add new instances of this fragment to the front of the ViewAnimator (However it can house 2 fragments at most, if the user requests a new fragment and size > 2 then the oldest fragment is removed using the FragmentTransaction instance).

I imagine a "worst-case" scenario where the user will flip through perhaps 30 fragments in a relatively short time-span, thus creating 30 separate threads. Is Android capable of managing all these threads(killing them etc.) by itself, or do I need to revise my code?

The reason each fragment uses its own thread, instead of the activity just using one for all of them, is for the sake of modulartiy. I imagined it would be best if the fragment was self-contained.

share|improve this question
In reply to myself, and to anyone interested: Apparently AsyncTask (which AsyncTaskLoader uses) manages it's own threadpool, so all management is taken care off behind the scenes. –  soren.qvist Mar 19 '12 at 21:22
add comment

1 Answer

up vote 3 down vote accepted

Excessive threading is always a bad idea. Threads tend to consume a lot of memory, and that memory can often be used for other things that will result in your app running faster. However is not clear if 30 would qualify as excessive on an Android device. The flip side of the performance issue is the (potential) complexity of managing thread numbers.

(If you start getting OOME's when starting threads, then the number of threads is definitely excessive ...)

I'd suggest using a bounded thread pool (e.g. a ThreadPoolExecutor) to cap the number of threads that can be running at any time. (Assuming that you have N cores to play with and the task is CPU bound, then there's no performance benefit in having more than N or N + 1 worker threads.) However, beware of situations there are scheduling / dependencies between different tasks, and a finite thread pool could lead to schedule induced deadlock.

share|improve this answer
Thanks for the good answer. Do you know if applications have separate fixed-size thread pools by standard? –  soren.qvist Mar 19 '12 at 20:29
Some do, some don't. It depends on the application requirements. However, it is a common strategy when you potentially have a large number of to tasks to perform "in parallel". A bounded thread pool actually serves two purposes: it limits the number of threads, and reduces the overheads of thread creation / destruction by recycling them. –  Stephen C Mar 19 '12 at 22:22
add comment

Your Answer


