简体   繁体   中英

Performance of ExecutorService in Java

I am trying to understand the ExecutorService in java. There is not much performance difference when I use 1 thread or 4 threads. I have a quad core CPU and I do not have any other process running.

ExecutorService exService = Executors.newFixedThreadPool(4);
exService.execute(new Test().new RunnableThread());
exService.awaitTermination(25, TimeUnit.SECONDS);

class RunnableThread implements Runnable {
        @Override
        public void run() {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            long cnt = 0;      
            for (cnt = 0; cnt < 999999999; cnt++) {
                try {
                    for (long j = 0; j < 20; j++){
                      x += j;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            stopWatch.stop();
            System.out.println(stopWatch.getTime());
        }
    }

If my understanding is right, my task should have close to 4x performance improvement when I say newFixedThreadPool(4) right?

Unfortunately, there is no magic in the allocation of workload to threads.

Every task runs on its own thread. It does not somehow automatically get transformed into concurrent execution paths.

If you have only one task, the remaining three threads will be idle.

Multiple threads only speed up things if you can split your workload into multiple tasks that can run concurrently (and you have to do that splitting yourself).

If my understanding is right, my task should have close to 4x performance improvement when I say newFixedThreadPool(4) right?

Yes, if you're actually running 4 concurrent tasks.

Currently, you have a single task that you are submitting to the executor. Let's say that it takes 10 seconds. Even if you have 4 cores and 4 threads, Java will not be able to parallelize a single task. However, if you submit 4 independent tasks (that have no memory or lock contention), then you will see all of them complete in those 10 seconds that it took the 1 task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM