Java – ThreadPoolExecutor More threads = slower android

ThreadPoolExecutor More threads = slower android… here is a solution to the problem.

ThreadPoolExecutor More threads = slower android

   BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
                ThreadPoolExecutor ex = new ThreadPoolExecutor(1,1, 1L, TimeUnit.MINUTES, queue);

final HashMap<String,Response> responses = new  HashMap<String,Response>();

ex.execute(new Runnable() {
                    @Override
                    public void run() {
                        android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_MORE_FAVORABLE);
                        Response response = getService().getProducts();
                        responses.put("1",response);

}
                });
....
....

...

ex.shutdown();
 ex.awaitTermination(1000, TimeUnit.DAYS);
 long  time2 = System.currentTimeMillis();

I’ve made a lot of requests and want to be notified when it’s done.

Testing

android 2.3 gingerbead on an older device with 1 thread ThreadPoolExecutor takes 1-1.2 seconds. It takes a much more 4-5 seconds to use 4 threads!

Testing on Galaxy tab 3 took 100ms for one thread and 60ms for 4 threads.

Why is this??

Solution

No matter how many threads you create, the number of physical cores in your processor is limited.

Older devices may have only one core, so as there are more threads, it must constantly jump between threads to process them.

New devices have multiple cores, so threads can be distributed on top of them and run in parallel.

In general, for intensive tasks, you should never start more threads than you have cores. For tasks that only run occasionally, more threads might be fine, but something like having a thread pool behind ScheduledExecutor would still be better.

Related Problems and Solutions