Ilya Vorobiev
Ilya Vorobiev

Reputation: 836

How to choose size of thread pool on android

I want to read multiple files from the sdcard in parallel with a ThreadPoolExecutor. What is the best way to choose number of Threads? Is it okay to choose the size based on the number of available processors?

Upvotes: 6

Views: 2840

Answers (1)

Xaver Kapeller
Xaver Kapeller

Reputation: 49837

Choosing the number of Threads 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 source code of AsyncTask:

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<Runnable> sPoolWorkQueue =
        new LinkedBlockingQueue<Runnable>(128);

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

I would consider this a best practice solution.

You can look at the source code of AsyncTask here if you want a better idea of how they use the ThreadPoolExecutor.

Upvotes: 8

Related Questions