How to schedule multiple tasks with ExecutorService

1.6k views Asked by At

I have three independend tasks to be executed at every 1 minute. Here I have developed two options.

Option1

ScheduledExecutorService service1 = Executors.newScheduledThreadPool(1); 
ScheduledExecutorService service2 = Executors.newScheduledThreadPool(1); 
ScheduledExecutorService service2 = Executors.newScheduledThreadPool(1); 
service1.scheduleAtFixedRate(new task1(), 0, 60, TimeUnit.SECONDS); 
service2.scheduleAtFixedRate(new task2(), 0, 60, TimeUnit.SECONDS); 
service3.scheduleAtFixedRate(new task3(), 0, 60, TimeUnit.SECONDS);

Option2

ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
service.scheduleAtFixedRate(new task1(), 0, 60, TimeUnit.SECONDS);
service.scheduleAtFixedRate(new task2(), 0, 60, TimeUnit.SECONDS);
service.scheduleAtFixedRate(new task3(), 0, 60, TimeUnit.SECONDS);

My question is which option is preferred? Does Option1 consume more system resources?

1

There are 1 answers

0
Tim Biegeleisen On

I don't know the implementation details to give an exact answer as to which usage would consume more system resources. But the second option is definitely the way which is supported by Javadoc, tutorials, etc. There are some reasons which I can point out. First, the ScheduledExecutorService interface exposes the ability to schedule multiple tasks with a single service.

There is also a reason to not use the first option. You were trying to schedule three tasks using three separate executors. But there is no guarantee that all three tasks would begin at the same time, but the executors are different and could be spun up at different times. On the other hand, if you used a single executor service the three tasks should be started concurrently.