Concurrency in real systems question 135 of 180 mid
Why can one slow @Scheduled job delay every other scheduled job in a Spring app?
- Spring deliberately runs scheduled jobs one at a time, to prevent races
- Correct: The default scheduler has a single thread, so a long job holds up every job due meanwhile
- Each job has its own thread, but they all share one lock
- The JVM allows only one scheduled task per core
Without configuration, Spring Framework schedules on a single-threaded executor, and Spring Boot's
auto-configured ThreadPoolTaskScheduler has spring.task.scheduling.pool.size=1. Every
@Scheduled method in the application shares that one thread. A report that takes ten minutes means
the cache refresh due every minute runs ten minutes late, and nothing in the logs says so.
The fixes, depending on what the jobs are:
- Raise
spring.task.scheduling.pool.size, or define your ownTaskSchedulerbean. - Keep the scheduled method short and hand the heavy work to a dedicated executor.
- On Boot 3.2 and later,
spring.threads.virtual.enabled=trueswitches scheduling to a virtual thread per run.
Two related facts come up in the follow-up. A single job never overlaps itself: with fixedRate, a
run that overruns makes the next one start late, not concurrently. And an exception is logged and the
schedule continues, unlike a raw ScheduledExecutorService, where one exception silently cancels
every future run. Finally, with several instances of the service, each one runs the job; making it
run once per cluster needs a lock outside the JVM, such as ShedLock.
Quiz yourself on Concurrency in real systems Suggest a correction