Reputation: 62519
Lets say i have a asyncTask like this:
public void startAsyncTask() {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
For those who dont know a asyncTask just creates a background thread. and anonymous classes are really non-static inner classes.
Now lets say in the activity (main thread) i call startAsyncTask()
the thread will take a little while to complete (about 5 minutes).
During the background threads lifetime, lets imagine the activity gets destroyed and its time to garbage collect the activity. Since the asyncTask has an implicit reference to the outer class (the activity) the activity will leak and will not be garbage collected.
But my question is the following: After some time, the child thread will eventually finish. Can the GC attempt to free memory again or is the activity forever leaked ? What i want to know really is if the child thread finishes in a reasonable amount of time will the activities memory be freed or is it only on the first attempt the GC tries and after that attempt the memory is forever lost ?
Upvotes: 0
Views: 99
Reputation: 39836
The garbage collector does not operate based on the activity life-cycle, it operates based on "are there any objects referencing it". So yeah, the activity memory will be freed after the thread finishes (and the AsyncTask is not referencing it anymore).
But that still is a memory leak of a very heavy object (the activity). And it's bad programming that shouldn't be done.
I'm not sure if you have an actual problem that you want to apply that, or is that a purely theoretical question on the inner workins of the VM, but if it's an actual problem that you want to apply that; the answer is: Don't do it!
Upvotes: 1