Can I rely on the garbage collector to stop AsyncTask?… here is a solution to the problem.
Can I rely on the garbage collector to stop AsyncTask?
A quick theoretical question. Let’s say I have a Java class that uses a finalizer and an instance of its own private AsyncTask that isn’t referenced anywhere else.
Now suppose AsyncTask’s doInBackground method looks like this:
while(go) {
f();
}
The terminator is:
public void finalize() {
go = false;
}
Does AsyncTask stop when all external references to an object are removed? Or does the system continue the thread and never deletes the object because it was referenced by the thread?
Solution
Can I rely on the garbage collector to stop an AsyncTask?
No, you can’t. In fact, you can trust that GC does not stop the task.
GC only terminates an object that has become inaccessible. But by definition, all activity threads are reachable, which means that the AsyncTask
object will also be reachable.