Sub topic 6
The scheduler thread pool
This chapter assumes you can declare @Scheduled methods, know the difference between fixedRate and fixedDelay, and can edit application.yml. It covers how many tasks can run at the same time and how to change that.
One thread by default
When @EnableScheduling is present, Spring Boot auto-configures a ThreadPoolTaskScheduler. Its pool size is 1. Every @Scheduled method in the application shares that one thread, so two tasks can never run at the same moment.
The following two jobs show the effect:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ContentionDemo {
private static final Logger log = LoggerFactory.getLogger(ContentionDemo.class);
@Scheduled(fixedRate = 2000)
public void quickJob() {
log.info("quick job on {}", Thread.currentThread().getName());
}
@Scheduled(fixedRate = 60000)
public void slowJob() throws InterruptedException {
log.info("slow job starts on {}", Thread.currentThread().getName());
Thread.sleep(10000);
log.info("slow job ends");
}
}With the default pool, quickJob goes silent for about 10 seconds while slowJob holds the only thread. Once the slow job ends, the overdue quick runs fire late. Spring does not run the missed executions in parallel. The log shows the same thread name for both jobs.
Configuring the pool
Set the pool size and related options with the spring.task.scheduling properties:
spring:
task:
scheduling:
thread-name-prefix: sched-
pool:
size: 4
shutdown:
await-termination: true
await-termination-period: 30s| Property | Purpose |
|---|---|
| `pool.size` | Number of threads available to scheduled tasks. |
| `thread-name-prefix` | Prefix for thread names, which makes log lines easier to trace. |
| `shutdown.await-termination` | Whether shutdown waits for running tasks to finish. |
| `shutdown.await-termination-period` | Maximum time to wait during shutdown. |
After you set pool.size: 4, the demo logs sched-1 and sched-2 as thread names, and quickJob keeps its rhythm while slowJob sleeps.
Choosing a pool size
- Count the tasks that may overlap in time, not the total number of tasks. Ten jobs that run for milliseconds each at different times need one thread.
- Add a thread for each task that can run long or block on I/O, such as an HTTP call or a database query.
- Keep the pool small. Each thread is memory, and scheduled tasks often share a database connection pool. Four scheduler threads that all need connections can starve your request handling.
A single task still does not overlap itself
A larger pool does not let the same method run twice at once. If a fixedRate task takes longer than its period, the next run starts as soon as the previous one ends. It does not start in parallel. If you want overlapping runs of one method, you must add @Async, which a later chapter covers.
Common errors
- Tasks start late and nobody knows why. The pool is too small. Compare the scheduled time with the log timestamp, and check the thread name.
- Raising the pool size and expecting parallel runs of one method. The scheduler still runs a given method one invocation at a time.
- Defining your own
TaskSchedulerbean and then finding the YAML properties ignored. Thespring.task.schedulingproperties configure only the auto-configured scheduler. If you supply your own bean, configure it in code.
Exercise
Your application has a fixedRate = 1000 task that takes 100 ms, and a nightly task that takes 5 minutes. With the default configuration, what happens to the first task during the nightly run, and what is the smallest change that fixes it?
Show answer
The default pool has one thread, so the nightly task holds it for 5 minutes and the one-second task cannot run until it finishes. The smallest fix is to set spring.task.scheduling.pool.size to 2 (or more). The nightly task then occupies one thread and the frequent task keeps running on the other.