Sub topic 6
The scheduler thread pool
This chapter assumes you can write a @Scheduled method, know the difference between fixedRate and fixedDelay, and understand basic thread concepts such as blocking and a thread pool. It covers which threads run your scheduled methods, how to configure them, and the errors that follow from the defaults.
Who runs your tasks
Spring does not run a @Scheduled method on the thread that created the bean. It registers the method with a TaskScheduler, and the scheduler runs it on one of its own threads. Spring Boot auto-configures a ThreadPoolTaskScheduler bean named taskScheduler when scheduling is enabled and you have not defined your own scheduler.
The default pool size is 1. Every @Scheduled method in the application shares that one thread. Two tasks never run at the same moment, even when their triggers fire together.
Seeing the problem
The following class has two jobs. The first sleeps for 12 seconds. The second is meant to run every 5 seconds.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class CollidingJobs {
private static final Logger log = LoggerFactory.getLogger(CollidingJobs.class);
@Scheduled(fixedRate = 20000)
public void slowJob() throws InterruptedException {
log.info("slowJob start");
Thread.sleep(12000);
log.info("slowJob end");
}
@Scheduled(fixedRate = 5000)
public void fastJob() {
log.info("fastJob");
}
}With the default pool, the log shows fastJob once at startup or just after slowJob end, then nothing for 12 seconds. Each log line also carries the thread name. By default it looks like scheduling-1, and it is the same for both jobs. That shared name is the quickest way to confirm that you are running on a single thread.
Configuring the pool
Spring Boot exposes the pool through spring.task.scheduling.* properties.
spring:
task:
scheduling:
thread-name-prefix: sched-
pool:
size: 4
shutdown:
await-termination: true
await-termination-period: 30s| Property | Default | Effect |
|---|---|---|
| `spring.task.scheduling.pool.size` | 1 | Number of scheduler threads |
| `spring.task.scheduling.thread-name-prefix` | `scheduling-` | Prefix for thread names in logs and thread dumps |
| `spring.task.scheduling.shutdown.await-termination` | `false` | Wait for running tasks when the context closes |
| `spring.task.scheduling.shutdown.await-termination-period` | none | Maximum wait time |
With pool.size: 4, fastJob runs on a second thread while slowJob sleeps. You will see names such as sched-1 and sched-2 in the log.
Choosing a size
There is no universal value. Use these criteria:
- Count the tasks that can overlap in time. If five jobs can fire together and all must start promptly, the pool needs at least five threads.
- Consider how long each task blocks. Tasks that wait on network or database calls hold a thread while idle, so they need more threads than CPU-bound tasks.
- Keep the pool modest. Each thread is a real OS thread, and tasks that all hit the same database can exhaust its connection pool.
If you cannot predict the overlap, size the pool by the number of scheduled methods, then watch for late starts in production.
One method never overlaps with itself
A larger pool does not let a single method run concurrently with itself. For one @Scheduled method, Spring schedules the next run only after the current run completes. This holds for both trigger styles:
- With
fixedDelay, the next run is measured from the end of the current one, so overlap cannot occur. - With
fixedRate, the next run is due at start time plus the rate. If a run takes longer than the rate, the next run starts late, immediately after the current one ends. Runs are not queued up in bulk, and they do not run in parallel.
So fixedRate = 5000 with a task that takes 12 seconds produces back-to-back runs, each starting as the previous one ends. The scheduler falls behind but it does not stack up concurrent copies.
Overlap does appear in one case. If you add @Async to the method, the scheduler thread returns at once and the next trigger fires on schedule, so runs of the same method can overlap. The @Async section below covers this.
Combining `@Scheduled` with `@Async`
@Async moves the work onto a separate executor and frees the scheduler thread immediately.
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Configuration
@EnableAsync
class AsyncConfig {
}
@Component
class SlowJobs {
@Scheduled(fixedRate = 60000)
@Async
public void slowTask() {
// runs on the async executor, so the scheduler thread is free immediately
}
}Two consequences follow.
- Other tasks no longer wait. The scheduler thread only hands work off, so one slow job cannot delay the rest.
- Runs can overlap. The scheduler no longer waits for completion, so a
slowTaskthat takes 90 seconds with a 60-second rate will have two runs active at once.fixedDelayloses its meaning too. The delay is measured from when the hand-off returns, not from when the work ends.
If overlap is unsafe, guard the method yourself, for example with an AtomicBoolean:
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class GuardedJob {
private final AtomicBoolean running = new AtomicBoolean(false);
@Scheduled(fixedRate = 60000)
@Async
public void slowTask() {
if (!running.compareAndSet(false, true)) {
return; // previous run still active, skip this one
}
try {
// long work
} finally {
running.set(false);
}
}
}This guard works inside one JVM only. Chapter coverage of multiple instances comes later in this tutorial.
Which executor does `@Async` use?
Boot also auto-configures a separate ThreadPoolTaskExecutor for @Async, configured under spring.task.execution.*. Its threads are named task- by default. It is a different pool from the scheduler, so tuning spring.task.scheduling.pool.size has no effect on @Async work.
Providing your own scheduler
Boot's auto-configured scheduler backs off if you define a TaskScheduler, a ScheduledExecutorService, or a SchedulingConfigurer that supplies one. In that case the spring.task.scheduling.* properties no longer apply to your bean, so set the values in code.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class SchedulerConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(4);
scheduler.setThreadNamePrefix("custom-sched-");
scheduler.setWaitForTasksToCompleteOnShutdown(true);
scheduler.setAwaitTerminationSeconds(30);
return scheduler;
}
}A common mistake is defining a custom bean and then wondering why the YAML pool size is ignored. The properties configure Boot's builder, and a hand-built scheduler does not use that builder.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| A task starts seconds or minutes late | Another task holds the single scheduler thread | Raise `pool.size` or move slow work to `@Async` |
| All tasks stop and never resume | A task blocks forever, such as a socket read with no timeout | Add timeouts to blocking calls |
| Pool size set in YAML has no effect | A custom `TaskScheduler` bean replaced the auto-configured one | Configure the size on your bean |
| Task runs twice at once | `@Async` added to a `fixedRate` method | Add an overlap guard or remove `@Async` |
| `@Async` method runs on the scheduler thread | Self-invocation bypasses the proxy | Move the method to another bean |
| Thread names do not match your prefix | You set the prefix under `execution` instead of `scheduling` | Use `spring.task.scheduling.thread-name-prefix` |
Checking your configuration
You can confirm the pool size without waiting for a collision. Inject the scheduler and read it:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class SchedulerDiagnostics {
private static final Logger log = LoggerFactory.getLogger(SchedulerDiagnostics.class);
@Bean
ApplicationRunner logSchedulerSize(ThreadPoolTaskScheduler scheduler) {
return args -> log.info("scheduler pool size = {}", scheduler.getPoolSize());
}
}getPoolSize() reports the number of threads currently created, which can be lower than the configured maximum until tasks have actually run. For the configured value, use scheduler.getScheduledThreadPoolExecutor().getCorePoolSize().
Exercise
An application has the default scheduler. Job A is @Scheduled(fixedRate = 10000) and takes 25 seconds. Job B is @Scheduled(fixedRate = 10000) and takes 1 second. Describe what happens to B, then name two changes that fix it and one risk each change introduces.
Show answer
B is starved. A holds the only scheduler thread for 25 seconds, so B starts late and cannot run on schedule. Fix 1: set spring.task.scheduling.pool.size to 2 or more. Risk: A and B can now run at the same time, so they must not share unsafe state, and the extra thread holds resources. Fix 2: add @Async to A (with @EnableAsync). Risk: A's runs can now overlap with each other, because the scheduler no longer waits for it to finish, so A needs an overlap guard.
Exercise
You set spring.task.scheduling.pool.size: 8 but the log still shows every task on one thread. You also have a @Bean TaskScheduler in a configuration class. What is the likely cause and the fix?
Show answer
The custom TaskScheduler bean replaced Boot's auto-configured scheduler, so the property is never applied. Set the pool size on the custom bean with setPoolSize(8), or remove the bean and rely on the properties.