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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With