shreyas
shreyas

Reputation: 2166

AsyncTask memory leak

does creating asyncTask like

AsyncTask<Void,Void,Void> newTask = new AsyncTask<Void,Void,Void>{
....
}
newTask.execute()

create memory leaks?

Upvotes: 4

Views: 4184

Answers (2)

Hamad
Hamad

Reputation: 5152

Yes: is your thread garbage collected after onPostExecute is called or is it still in the memory?

An Async Task will not be canceled or destroyed at the moment the activity is dismissed. If your thread is more or less lightweight and finishes after a small time, just keep it running and add a yourActivity.this.isFinishing() clause in the onPostExecuteMethod.

Upvotes: 0

Hamad
Hamad

Reputation: 5152

ok then @sherays Especially in Your case, If you execute another request to the server while previous one is not finished yet (in case of similar requests), this is a chance of memory leak.

Actually, there shouldn't be any issue with AsyncTask recycling unless You hold any reference to it from param or generate memory leaks inside doInBackground().

So, You might think, that if You're creating many long-running AsyncTasks then it would lead to some memory issues. Actually it's not true (at least on latest Android versions). AsyncTask source code shows that

It uses singleton bounded executor:

private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final int KEEP_ALIVE = 1;

public static final Executor THREAD_POOL_EXECUTOR
    = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
            TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

That means that executor won't run more than 128 AsyncTasks the same time (128 is not very big per my understanding).

It uses bounded query for the Executor:

private static final BlockingQueue<Runnable> sPoolWorkQueue =
        new LinkedBlockingQueue<Runnable>(10);

So, based on the above points, number of created and running the same time AsyncTasks are limited and not so big. So, if Your code inside AsyncTask doesn't create any memory leaks, then per my understanding there's no issue. Same time Android won't let You spam itself with AsyncTasks. Checkout ThreadPoolExecutors description to get familiar with the way it manages a memory (If You worry about too many created threads the same time).

so still,if you face memory leak then cancel the task:

Regarding cancel() call, based on Android documentation for AsyncTask:

Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

Upvotes: 4

Related Questions