5

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 ?

j2emanue
  • 60,549
  • 65
  • 286
  • 456

1 Answers1

5

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.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • i see. I do not know why anyone would do a non-static inner class in this case. I'll convert it to a nested static inner class to avoid leakage. – j2emanue Sep 22 '16 at 15:03
  • Every inner class that can be should be static- really they ought to have made it the default. THe big reason for not being static is if you need to reference variables/functions of the parent in the inner class- in that case it can't be static. – Gabe Sechan Sep 22 '16 at 15:09