In this code I create ScheduledExecutorService with pool of 5 threads
and call scheduleWithFixedDelay method 5 tims. It will create 5 schedulers and each scheduler will call testBean::test every secons:
@PostConstruct
public void hz() {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5, new ThreadPoolTaskScheduler());
for (int i = 0; i < 5; i++) {
scheduledExecutorService.scheduleWithFixedDelay(testBean::test, 1, 1, TimeUnit.SECONDS);
}
}
But I have somw questions.
Do I understand correctly that
ScheduledExecutorServicejust java interface andThreadPoolTaskScheduler()- is spring i,plementation?Does it exist spring analog instead
ScheduledExecutorService?The most important question. What happens if I try to call the
scheduleWithFixedDelaymethod more times than the pool inScheduledExecutorService(for example 9)?:
@PostConstruct public void hz() { ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5, new ThreadPoolTaskScheduler()); for (int i = 0; i < 9; i++) { scheduledExecutorService.scheduleWithFixedDelay(testBean::test, 1, 1,TimeUnit.SECONDS); } }
The short answer is that any scheduled task you submit gets priority queued (based on the time when its supposed to run) in the global queue of your thread pool. The individual threads then pick up the tasks and execute them in order. So, in your case, at t=1, the 5 threads in the pool will pick 5 items from the queue and execute them in parallel. As they complete the execution, next 4 items will get picked at time=(1 + time it takes to execute your callback function). So, unless your call back function hogs the thread for few seconds, all the 9 scheduled tasks should execute approximately at t=1.