Reputation: 541
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
Upvotes: 0
Views: 476
Reputation: 7792
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.
Upvotes: 1
Reputation: 768
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.
Upvotes: 0