Friday, January 18, 2019

Custom Thread Pool for Schedule job in SpringBoot

By default, default thread pool is used for schedule job. Number of thread in this pool is small. If we have many scheduled tasks, they could be delayed. We need to declare a dedicated thread pool for scheduled tasks. Below is an example thread pool (pool size 8) in Spring Boot.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
 
import javax.annotation.PreDestroy;
 
@Configuration
public class CustomSchedulingConfigure implements SchedulingConfigurer {
 
    ThreadPoolTaskScheduler pool = new ThreadPoolTaskScheduler();
 
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        pool.setPoolSize(8);
        pool.initialize();
        pool.setThreadNamePrefix("CustomPool");
        scheduledTaskRegistrar.setTaskScheduler(pool);
    }
 
    @PreDestroy
    public void stop() {
        pool.shutdown();
    }
}