Reputation: 7416
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.
Upvotes: 1
Views: 412
Reputation: 719596
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.
Upvotes: 3