Search code examples
javaandroidandroid-asynctask

Custom max asyncTasks in Android


I am creating an app and it needs to execute exactly 128 tasks at the same time. I have read that the maximum is 128 but it only does 20 on my emulator. How to make him do more or how to edit max async tasks?

Some info: API 29

I am calling them with this method:

@TargetApi(11)
static public <T> void executeAsyncTask(AsyncTask<T, ?, ?> task, T... params) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    } else {
        task.execute(params);
    }
}

This is supposed to work but it runs only 20 at the same time


Solution

  • The default maximum thread pool size for AsyncTask.THREAD_POOL_EXECUTOR is 20, that's the reason why you don't see more than this executed concurrently.

    If you want to have a bigger pool size you can define your own Executor:

    @TargetApi(11)
    static public <T> void executeAsyncTask(AsyncTask<T, ?, ?> task, T... params) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            Executor executor = new ThreadPoolExecutor(1, 128,
                                      5, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
            task.executeOnExecutor(executor, params);
        } else {
            task.execute(params);
        }
    }