I have 2 tasks t1 and t2. How should i schedule them. Both have there own delay {d1, d2} and period {p1, p2}.
Approach 1:
Should I use
ScheduledExecutorService ser = Executors.newScheduledThreadPool(2);
ser.scheduleAtFixedRate(t1, 1, 3, TimeUnit.SECONDS);
ser.scheduleAtFixedRate(t2, 2, 5, TimeUnit.SECONDS);
Here i have used thread pool size of 2. So both tasks can run parallel . But if one task wont be running thread will be idle.
Whereas if i would have taken thread pool size of 1. Only one tasks will be able to run at a time.
Approach 2:
ScheduledExecutorService ser1 = Executors.newScheduledThreadPool(1);
ScheduledExecutorService ser2 = Executors.newScheduledThreadPool(1);
ser1.scheduleAtFixedRate(t1, 1, 3, TimeUnit.SECONDS);
ser2.scheduleAtFixedRate(t2, 2, 5, TimeUnit.SECONDS);
Here i have used 2 ScheduledExecutorService one per task.
What will be the differences/advantages-disadvantages internally in both the approaches?
I would definitely expect to see the first one in most code. The idea of a thread pool is literally that you have a pool of threads around for use as required. You can manage them all at once through through the executor. Also, since its a limited/bounded pool, you ensure that if too many tasks get sent, you don't run them all at once (so, its like a safeguard).
Creating separate thread pools doesn't make sense; it loses these benefits... and you could just create a simple Timer in that case for each task.
If you really care about this level of detail, you can actually gain more control over the thread pool (e.g. cancel idle threads after a specifc amount of time). Check out this: https://www.codejava.net/java-core/concurrency/java-concurrency-understanding-thread-pool-and-executors.
It's not specific to Scheduled Thread Pools, but I can pretty much guarantee that if you dig around you can achieve the same things with them.