Video in progress

Strong Middle 🧵 Concurrency

In Spring I have several @Scheduled methods, and when one of them gets slow, the others are delayed too. Why?

By default Spring Boot creates a single-threaded ThreadPoolTaskScheduler for scheduling. All @Scheduled methods run on that one thread in turn, so one long task blocks the rest. You need to increase the pool size or move the heavy work to a separate executor.

📖 Answer

A typical case: one service has a "clean up stale sessions" job that runs every minute and a "send the report" job that runs every hour. The report took 20 minutes, and for those 20 minutes the cleanup didn't run once.

In a thread dump you see a single scheduling-1 thread, and that's all there is.

The first fix is the pool size:

spring:
  task:
    scheduling:
      pool:
        size: 4
      thread-name-prefix: sched-

But that's only the start. It's more correct to take the heavy work off the scheduler thread:

@Scheduled(cron = "0 0 * * * *")
public void triggerReport() {
    reportExecutor.execute(reportService::generateDaily);   // the scheduler is free right away
}

A few subtle points:

  • with a pooled scheduler, one method doesn't run in parallel with itself, even if the pool is large. That's good if you don't want overlapping runs;
  • if the service runs in several pods, each pod runs its own schedule. If you need "only one instance runs it", use ShedLock or a lock in the DB;
  • in Spring Boot 3.2+, with spring.threads.virtual.enabled=true, SimpleAsyncTaskScheduler is used instead of the scheduler, and tasks run on virtual threads. The blocking between tasks goes away, but the behavior changes, so read the docs before you turn it on.

I add a duration metric (a Micrometer timer) to every @Scheduled method, so a slowdown shows up on the graph right away.