Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask threads never die

I'm using AsyncTasks to fetch data in response to the user pressing a button. This works well and keeps the interface responsive while fetching the data, but when I checked out what was going on in the Eclipse debugger, I found out that every time a new AsyncTask was created (which is quite often, because they can only be used once), a new thread was being created but never terminated.

The result is a large number of AsyncTask threads just sitting there. I'm not sure if this is a problem in practice or not, but I'd really like to get rid of those extra threads.

How can I kill these threads?

like image 811
Computerish Avatar asked Jun 19 '10 22:06

Computerish


People also ask

Can an AsyncTask be executed in a worker thread?

According to Android doco you must run an AsyncTask from a UI thread, but in reality it depends on who runs this line in AsyncTask.

What is the difference between AsyncTask and thread?

Thread can be triggered from any thread, main(UI) or background; but AsyncTask must be triggered from main thread. Also on lower API of Android(not sure, maybe API level < 11), one instance of AsyncTask can be executed only once. Long task in general.

What happens to AsyncTask if activity is destroyed?

If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.


1 Answers

AsyncTask manages a thread pool, created with ThreadPoolExecutor. It will have from 5 to 128 threads. If there are more than 5 threads, those extra threads will stick around for at most 10 seconds before being removed. (note: these figures are for the presently-visible open source code and vary by Android release).

Leave the AsyncTask threads alone, please.

like image 137
CommonsWare Avatar answered Oct 19 '22 09:10

CommonsWare