Question
What is the default scheduler pool size in Spring Boot?
@Service
public class ZipFileTesterAsync {
@Scheduled(fixedDelay = 60000, initialDelay = 500)
public void run() throws Exception {
System.out.println("import 1");
TimeUnit.MINUTES.sleep(1);
System.out.println("import 1 finished");
}
@Scheduled(fixedDelay = 60000, initialDelay = 1000)
public void run2() throws Exception {
System.out.println("import 2");
TimeUnit.MINUTES.sleep(1);
}
}
Answer
In Spring Boot, when using the `@Scheduled` annotation without a specific configuration, tasks by default execute in a single-threaded pool. This means that if one scheduled task is running, others will wait to execute until the current one completes.
@Configuration
public class SchedulerConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(5); // Set your desired pool size
scheduler.setThreadNamePrefix("ScheduledTask-");
return scheduler;
}
}
@Service
public class ZipFileTesterAsync {
@Scheduled(fixedDelay = 60000, initialDelay = 500)
public void run() throws Exception {
System.out.println("import 1");
TimeUnit.MINUTES.sleep(1);
System.out.println("import 1 finished");
}
@Scheduled(fixedDelay = 60000, initialDelay = 1000)
public void run2() throws Exception {
System.out.println("import 2");
TimeUnit.MINUTES.sleep(1);
}
}
Causes
- The default thread pool for scheduled tasks is a single-thread executor, which means only one task is executed at a time.
- If a scheduled method takes a long time to execute, it blocks other scheduled methods from running concurrently.
Solutions
- To enable parallel execution of scheduled tasks, you can configure a task scheduler with a thread pool size greater than one.
- You can define a `ThreadPoolTaskScheduler` bean in your configuration class to set a custom thread pool size.
Common Mistakes
Mistake: Not configuring a ThreadPoolTaskScheduler, leading to sequential execution.
Solution: Define a TaskScheduler bean with multiple threads to allow concurrent execution of scheduled tasks.
Mistake: Using long-running tasks within a scheduled method without proper thread management.
Solution: Optimize task execution time or split tasks into smaller, non-blocking calls.
Helpers
- Spring Boot
- Scheduler Pool Size
- Spring Boot @Scheduled
- Concurrency in Spring Boot
- Task Scheduler Configuration