Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadPoolExecutor more threads=slower android

Tags:

java

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 make many requests that I want to be notified when finished.

Testing on android 2.3 gingerbead on old device with ThreadPoolExecutor with 1 thread takes 1-1.2 seconds. Using 4 threads takes lot more 4-5 seconds!.

Testing on galaxy tab 3 it takes with one thread 100 milliseconds with 4 it takes 60 ms.

Why does this happen ??

like image 872
GorillaApe Avatar asked Apr 22 '26 08:04

GorillaApe


1 Answers

No matter how many threads you create, you only have so many physical cores in your processor.

The older device probably has one core, so with more threads it constantly has to jump between the threads to process them.

The new device has multiple cores so can spread the threads out over them and run them 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 can be ok but something like a ScheduledExecutor with a thread pool behind it would still be better.

like image 113
Tim B Avatar answered Apr 24 '26 22:04

Tim B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!