Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose size of thread pool on android

Tags:

java

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?

like image 689
Ilya Vorobiev Avatar asked May 18 '15 03:05

Ilya Vorobiev


People also ask

How is thread pool size defined?

The size of a thread pool is the number of threads kept in reserve for executing tasks. It is usually a tunable parameter of the application, adjusted to optimize program performance. Deciding the optimal thread pool size is crucial to optimize performance.

What is the maximum size of thread pool?

Starting thread pool size is 1, core pool size is 5, max pool size is 10 and the queue is 100. As requests come in, threads will be created up to 5 and then tasks will be added to the queue until it reaches 100. When the queue is full new threads will be created up to maxPoolSize .

What is thread pool queue size?

Thread pool type is fixed with a size of 1 , queue size of 16 .


1 Answers

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.

like image 188
Xaver Kapeller Avatar answered Sep 23 '22 14:09

Xaver Kapeller