Permalink
Browse files

Prevent AsyncTask from creating too many threads

Bug #10228005

From the ThreadPoolExecutor documentation:

  - If fewer than corePoolSize threads are running, the Executor
    always prefers adding a new thread rather than queuing.
  - If corePoolSize or more threads are running, the Executor
    always prefers queuing a request rather than adding a new thread.
  - If a request cannot be queued, a new thread is created unless
    this would exceed maximumPoolSize, in which case, the task will
    be rejected.

Before this change AsyncTask could create up to 128 threads because
of the limited queue of 10 items (the capacity of a blocking queue
is fixed.)

This change increases the size of the queue to 128 items and reduces
the maximum number of threads to the number of CPU cores * 2 + 1.
Apps can still submit the same number of tasks.

Change-Id: I015d77b53b6a9fda39c618830b34d45a10de5571
  • Loading branch information...
romainguy committed Aug 9, 2013
1 parent d81a15c commit 719c44e03b97e850a46136ba336d729f5fbd1f47
Showing with 4 additions and 3 deletions.
  1. +4 −3 core/java/android/os/AsyncTask.java
@@ -177,8 +177,9 @@
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";

private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;

private static final ThreadFactory sThreadFactory = new ThreadFactory() {
@@ -190,7 +191,7 @@ public Thread newThread(Runnable r) {
};

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

/**
* An {@link Executor} that can be used to execute tasks in parallel.

0 comments on commit 719c44e

Please sign in to comment.