Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android anonymous asyncTask - will it cause memory leak

Tags:

In android i am trying to prevent a memory leak. I inherited some legacy code and in it the developer is creating a asyncTask as a 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 am using a loop in this example just to keep the child thread alive forever so i can demo my point. so from the activity if i call startAsyncTask() will there be a memory leak ? the class does not have a activity reference but i realize that an anonymous class is really a non-static inner class and thus holds a reference to the outer class. so is it true that this itself is a memory leak ?

like image 791
j2emanue Avatar asked Sep 22 '16 14:09

j2emanue


1 Answers

It will hold a reference to the outer class (the Activity) until the task finishes. So it will cause the activity to be held longer than absolutely necessary. However if the task finishes in a reasonable amount of time, that ought to be ok- after its finished the task will be over and become garbage collectable, which will make the Activity garbage collectable. The bigger concern is long term threads which can last well past the end of the activity, or not terminate at all if poorly written.

like image 106
Gabe Sechan Avatar answered Sep 25 '22 16:09

Gabe Sechan