简体   繁体   中英

Multiple ScheduledExecutorServices or one with a ThreadPool for Fixed Rate Tasks

Consider a hypothetical case in which multiple tasks will run permanently in fixed rates. The number of these tasks will not change as long as the application runs. For such a case, is there any difference between creating a thread pool with n tasks like this

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(n);
for (int i = 0; i < n; i++) {
    executorService.scheduleAtFixedRate(job, 0, 5, TimeUnit.MINUTES);
}

and creating single executor for each task as given below?

for (int i = 0; i < n; i++) {
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(job, 0, 5, TimeUnit.MINUTES);
}

If there is any difference, which one should be preferred and why?

Note: Aside from creating multiple executor instances

The executor is meant to handle a pool of threads. So you don't need to create N Executors with a single thread as you end up with N instances of executors and N threads. Just hold one Executor that handles the N threads and you saved some memory by having 1 executor and N threads.

  1. The first one will create one executor with fixed number of threads.
  2. The second one will create n executors each with single thread.

The difference is that later on you could re-configure number of threads in newScheduledThreadPool. You would not be able to change number of threads in newSingleThreadScheduledExecutor. Also when creating multiple executors you would end up with 5 objects instead of one (creating just one executor). Personally, I would go with 1st option.

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