× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to choose size of thread pool on android

Xaver Kapeller
May 22, 2015
<p>Choosing the number of <code>Threads</code> based on the number of processors is a pretty good solution because it scales based on the hardware of the device which is running the app. A good example of this can be found in the <a href="http://grepcode.com/file/repo1.maven.org/maven2/org.robolectric/android-all/5.0.0_r2-robolectric-0/android/os/AsyncTask.java" rel="nofollow"><strong>source code</strong></a> of <code>AsyncTask</code>:</p> <pre><code>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() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final BlockingQueue&lt;Runnable&gt; sPoolWorkQueue = new LinkedBlockingQueue&lt;Runnable&gt;(128); public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); </code></pre> <p>I would consider this a best practice solution.</p> <p>You can look at the source code of <code>AsyncTask</code> <a href="http://grepcode.com/file/repo1.maven.org/maven2/org.robolectric/android-all/5.0.0_r2-robolectric-0/android/os/AsyncTask.java" rel="nofollow"><strong>here</strong></a> if you want a better idea of how they use the <code>ThreadPoolExecutor</code>.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30294794/How%20to%20choose%20size%20of%20thread%20pool%20on%20android/30297237">Stack Overflow</a>.</p>
comments powered by Disqus