From 719c44e03b97e850a46136ba336d729f5fbd1f47 Mon Sep 17 00:00:00 2001 From: Romain Guy Date: Fri, 9 Aug 2013 16:09:44 -0700 Subject: [PATCH] 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 --- core/java/android/os/AsyncTask.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/core/java/android/os/AsyncTask.java b/core/java/android/os/AsyncTask.java index ce5f1633a8cd5..d4a30064707ee 100644 --- a/core/java/android/os/AsyncTask.java +++ b/core/java/android/os/AsyncTask.java @@ -177,8 +177,9 @@ import java.util.concurrent.atomic.AtomicInteger; public abstract class AsyncTask { 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 abstract class AsyncTask { }; private static final BlockingQueue sPoolWorkQueue = - new LinkedBlockingQueue(10); + new LinkedBlockingQueue(128); /** * An {@link Executor} that can be used to execute tasks in parallel.