Sobes.tech
Junior — Middle

How can using AsyncTask lead to memory leaks in an application?

sobes.tech AI

Answer from AI

AsyncTask in Android can lead to memory leaks if it is declared as an inner class of an Activity or another component with a lifecycle, and continues to run after the Activity is destroyed.

The reason is that AsyncTask holds an implicit reference to the outer class (e.g., Activity). If the task runs for a long time and the Activity is already destroyed (for example, during a screen rotation), AsyncTask keeps a reference to the Activity, preventing the garbage collector from freeing the memory.

To avoid leaks:

  • Make AsyncTask a static class and use weak references (WeakReference) to the Activity.
  • Cancel the AsyncTask in the Activity's lifecycle methods (e.g., onDestroy).

Example:

static class MyTask extends AsyncTask<Void, Void, Void> {
    private WeakReference<Activity> activityRef;

    MyTask(Activity activity) {
        activityRef = new WeakReference<>(activity);
    }

    @Override
    protected Void doInBackground(Void... voids) {
        // Long operation
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        Activity activity = activityRef.get();
        if (activity != null && !activity.isFinishing()) {
            // Update UI
        }
    }
}
How can using AsyncTask lead to memory leaks in an… - sobes.tech