Java – android anonymous asyncTask – Does it cause a memory leak?

android anonymous asyncTask – Does it cause a memory leak?… here is a solution to the problem.

android anonymous asyncTask – Does it cause a memory leak?

In android, I try to prevent memory leaks. I inherited some legacy code where the developer created an asyncTask as an anonymous inner class like this:

 void startAsyncTask() {
    new AsyncTask<Void, Void, Void>() {
        @Override protected Void doInBackground(Void... params) {
            while(true);//loop  to keep thread alive forever.
        }
    }.execute();
}

So I used a loop in this example, just to keep the child thread in the activity state forever so I could demonstrate my point.
So if I call startAsyncTask() from the activity, will there be a memory leak? The class doesn’t have an activity reference, but I realized that the anonymous class is actually a non-static inner class, so holds a reference to the outer class. So is it true that this in itself is a memory leak?

Solution

It will hold a reference to the external class (Activity) until the task is completed. As a result, this causes the activity to take longer than is absolutely necessary. However, if the task completes in a reasonable amount of time, that should be fine – when finished, the task ends and becomes recyclable, which will make the activity recyclable. The bigger problem is long-lived threads, which can last long after the activity ends, or not terminate at all if poorly written.

Related Problems and Solutions