Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AsyncTask remains in running state after completing

While working on an application I noticed that the thread count keeps growing all the time. AsyncTask threads remain open for some reason (I'm sure they finished processing and exited). I have no idea why I keep creating more threads of this type and they keep running indefinitely.

Is there any way to verify that these threads are terminated on completion? Are there any known issues with AsyncTask threads remaining open?

When running this:

public  class DoNothingTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            return null;
        }

    }

I see in the debbuger a new thread for each time I do new DoNothingTask().execute(null); as follows:

Thread[<ThreadNumber>AsyncTask#1](running)

My question is why is this? My application relies a lot on AsyncTask and I can't have a new thread created and stay alive after each task.

like image 369
totem Avatar asked Aug 17 '10 09:08

totem


2 Answers

I was banging my head on this as well, and just came across this answer (well, it's more an explanation than an answer):

CommonsWare explains:

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.

Source question: AsyncTask threads never die

like image 169
defbyte Avatar answered Nov 14 '22 16:11

defbyte


I am not sure if this is related, but i faced similar issue in one of my applications too.

I have an activity which initializes TimerTask threads. The tasks get executed properly at the interval specified, but after some idle time, the number of these threads seem to be increased (showing that the threads remained open and new threads get created). The problem was dynamic loading and unloading of my application by Android VM. The original threads never used to get killed where as on every new load of application, the thread initialization used to happen. This is why total number of threads in my application used to rise.

Is there a similar implementation in your application as well.

like image 27
Tushar Tarkas Avatar answered Nov 14 '22 17:11

Tushar Tarkas