Can Bayar
Can Bayar

Reputation: 541

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

Upvotes: 0

Views: 476

Answers (2)

Michael Gantman
Michael Gantman

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

Guts
Guts

Reputation: 768

  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.

Upvotes: 0

Related Questions