Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask thread still there after execute, is that normal?

when I use AsyncTasks checking in the DDMS, the thread persist in memory as waiting thread after the onPostExecute() method, is that normal?. Here is a simplified Activity that reproduces my problem:

package com.example.async;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class ASyncTaskExampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    new ExampleAsyncTask().execute();
}


private class ExampleAsyncTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        for (int i =0; i<50000;i++){
            int j=i*2;
        }
        return null;
    }

    protected void onPostExecute(Void result) {
        Log.d("Test","End onPostExecute");
     }

}

}

like image 676
ChyBy Avatar asked Jul 15 '11 23:07

ChyBy


1 Answers

AsyncTask uses "thread pool" technique. Each AsyncTask you start gets into a queue; there are some idle threads in the "pool" (or they are created as needed up to a certain limit) waiting for tasks. An idle thread from the pool takes your AsyncTask and executes it, then returns to the pool. Then the process repeats until there are no more tasks in the queue.

This approach has 2 important features:

  1. no overhead for creating a thread every time
  2. in case of huge number of tasks system performance degrades gracefully: most of the tasks will wait in the queue and only few of them will be executed at a time; eventually all of them will get executed. Otherwise, if a separate thread was started for each task, the system would likely run out of memory or threads, or tasks will take forever to finish.

The thread which you see in DDMS after your AsyncTask finished is the idle thread in the pool.

like image 147
JBM Avatar answered Sep 27 '22 21:09

JBM