AsyncTask stream is still there after execution, is this normal?

when I use AsyncTasks check in DDMS, the thread is stored in memory as a 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"); } } 

}

+6
source share
3 answers

AsyncTask uses the thread pool method. Each AsyncTask you run enters the queue; in the "pool" (or they are created as necessary to a certain limit) there are several idle threads waiting for tasks. A simple thread from the pool takes your AsyncTask and executes it, and then returns to the pool. The process then repeats until there are more tasks in the queue.

This approach has two important functions:

  • no overhead to create a stream every time
  • in the case of a huge number of tasks, system performance deteriorates gracefully : most tasks will wait in line, and only a few of them will be performed at the same time; eventually they will all be fulfilled. Otherwise, if a separate thread was started for each task, the system would probably run out of memory or threads, or the tasks would end permanently.

The thread that you see in DDMS after AsyncTask shuts down is an idle thread in the pool.

+7
source

yep this avoids the overhead of killing and restarting the stream when sending the next AsyncTask

if you send another AsyncTask after the completion of the first, the same thread will be reused for it

+3
source

Both of the answers given here are correct. In addition to this, the status of such flows in the pool will be "wait". This phenomenon can also be observed when using libraries such as Okhttp, which use the connection pool for network operations.

0
source

Source: https://habr.com/ru/post/892868/


All Articles