Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule multiple tasks with ExecutorService

Tags:

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?

like image 609
CLI Avatar asked Dec 21 '16 15:12

CLI


1 Answers

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.

like image 152
Tim Biegeleisen Avatar answered Sep 23 '22 16:09

Tim Biegeleisen