Sub topic 13
Scheduling with virtual threads
This chapter assumes you know @Scheduled, the default single-thread scheduler pool, and the spring.task.scheduling properties from earlier chapters. You also need Java 21 or later and Spring Boot 3.2 or later.
Why virtual threads matter here
The default scheduler runs every task on a small pool of platform threads, and the default pool size is one. A task that blocks on a slow HTTP call or database query holds its thread for the whole wait, so other tasks queue behind it. Raising spring.task.scheduling.pool.size helps, but you must pick a number.
A virtual thread is a lightweight thread managed by the JVM. Blocking on I/O parks it cheaply instead of holding an operating-system thread. You can start one per task run without worrying about pool limits.
Turning it on
One property switches Spring Boot over:
spring:
threads:
virtual:
enabled: trueWith this property set, Boot auto-configures a SimpleAsyncTaskScheduler instead of the pool-based scheduler. It uses a single scheduler thread to decide when each trigger fires. It runs each task execution on a new virtual thread. Boot also switches the @Async executor to virtual threads.
@Component
public class ExportJobs {
private static final Logger log = LoggerFactory.getLogger(ExportJobs.class);
@Scheduled(fixedDelay = 10000)
public void exportOrders() throws InterruptedException {
log.info("export on {}", Thread.currentThread());
Thread.sleep(8000); // stands in for a blocking remote call
}
@Scheduled(fixedRate = 2000)
public void heartbeat() {
log.info("heartbeat on {}", Thread.currentThread());
}
}The log shows VirtualThread[...] for both methods. The heartbeat keeps its two-second rhythm while exportOrders sleeps. On the default one-thread pool it would stall.
What changes and what does not
| Aspect | Default pool | Virtual threads |
|---|---|---|
| Thread per run | Shared pool thread | New virtual thread |
| `spring.task.scheduling.pool.size` | Sets the pool size | Has no effect |
| Tasks blocking each other | Yes, if the pool is small | Not through thread exhaustion |
| Cron, `fixedRate`, `fixedDelay` semantics | Unchanged | Unchanged |
| Duplicate runs on several instances | Still a problem | Still a problem |
Triggers, time zones, property placeholders and error handling work as before. The scheduler still logs an exception thrown by a task, and later runs still happen.
Gotchas
- Overlap. Removing the thread limit also removes the natural queueing that kept runs apart. A
fixedDelaytask still waits for its own previous run to finish. Do not assume a slowfixedRatetask is serialized. Test it, and add a guard such as anAtomicBooleanif overlap would be harmful. - Pinning. On Java 21 through 23, a virtual thread that blocks inside a
synchronizedblock holds on to its carrier platform thread. Many such tasks can exhaust the carriers. PreferReentrantLockfor code that blocks while holding a lock. - CPU-bound work. Virtual threads help with waiting, not computing. A task that burns CPU for minutes gains nothing and competes with the rest of the application.
- Unbounded concurrency. Each run gets its own thread, so a task that triggers frequently and hangs can pile up thousands of threads. Set timeouts on remote calls.
- Defining your own scheduler. If you declare a
TaskSchedulerbean, Boot's auto-configuration backs off and the property no longer applies to scheduling.
Exercise
You enable spring.threads.virtual.enabled=true and keep spring.task.scheduling.pool.size: 4 in your configuration. A @Scheduled(fixedRate = 1000) task now sometimes takes 3 seconds because of a slow API. What do you check before relying on this setup in production?
Show answer
The pool size setting no longer has any effect, because the virtual-thread scheduler starts a new thread for each run. Check whether runs of the slow task can overlap, since the old thread limit no longer prevents it. If overlap is harmful, add a guard or switch to fixedDelay. Also set a timeout on the API call, and check the task for synchronized blocks that wrap blocking calls, which pin carrier threads on Java 21 through 23.