Sub topic 13
Scheduling with virtual threads
Earlier chapters configured the scheduler as a pool of platform threads. This chapter covers what changes when you run on Java 21 or later and turn on virtual threads. It assumes you know @Scheduled, the spring.task.scheduling properties, and the pool-size problem from the thread pool chapter.
What virtual threads change
A virtual thread is a lightweight thread managed by the JVM. Many virtual threads share a small set of operating system threads, called carrier threads. When a virtual thread blocks on I/O, the JVM unmounts it from its carrier. The carrier can then run other work.
This matters for scheduling because the usual failure mode is a pool that is too small. With the default single-thread scheduler, one task that waits 40 seconds on an HTTP call delays every other task. Raising spring.task.scheduling.pool.size helps, but you must guess a number. Virtual threads remove the guess for tasks that mostly wait.
Virtual threads do not make work faster. A task that spends its time computing still occupies a carrier thread, and the number of carriers is about the number of CPU cores.
Prerequisites and switch
You need Java 21 or later and Spring Boot 3.2 or later. Then set one property:
spring:
threads:
virtual:
enabled: true
task:
scheduling:
thread-name-prefix: sched-No code changes are needed. Your existing @Scheduled methods keep working.
What Spring Boot configures
With the property enabled, Spring Boot swaps the scheduler implementation. The table compares the two setups.
| Aspect | Default (platform threads) | `spring.threads.virtual.enabled=true` |
|---|---|---|
| Auto-configured bean | `ThreadPoolTaskScheduler` | `SimpleAsyncTaskScheduler` |
| Threads running tasks | Fixed pool, default size 1 | A new virtual thread per execution |
| `spring.task.scheduling.pool.size` | Sets the pool size | Ignored |
| Concurrency cap | Pool size | None, unless you set `spring.task.scheduling.simple.concurrency-limit` |
| Thread names | Prefix plus pool index | Prefix plus a running counter |
SimpleAsyncTaskScheduler keeps one internal thread that decides when each trigger fires. When a trigger fires, it starts a fresh virtual thread to run your method. So the timing logic is cheap and separate from the work, and a slow task cannot block the trigger for another task.
The @Async executor changes the same way. The auto-configured applicationTaskExecutor becomes a SimpleAsyncTaskExecutor that uses virtual threads, so @Async methods also run on virtual threads.
Verifying what runs where
Do not assume the switch took effect. Log the thread type from a task:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ThreadProbe {
private static final Logger log = LoggerFactory.getLogger(ThreadProbe.class);
@Scheduled(fixedDelay = 10000)
public void probe() {
Thread t = Thread.currentThread();
log.info("thread={} virtual={}", t.getName(), t.isVirtual());
}
}With the property enabled you should see virtual=true and a name starting with sched-. If you see virtual=false, check three things: the Java version, the Boot version, and whether you declared your own TaskScheduler bean. A custom TaskScheduler bean makes Boot's auto-configuration back off, and then the property has no effect on scheduling.
Tasks can now run concurrently
With a one-thread pool, two different @Scheduled methods never ran at the same time. With one virtual thread per execution, they can, and so can two runs of the same method. Review these cases:
- Two different jobs that touch the same data now race. Before, the single thread serialized them by accident.
- A
fixedRatejob whose run time exceeds its period may start a second run before the first finishes. - Jobs that relied on being single-threaded and kept state in plain fields are no longer safe.
How the new scheduler treats overlapping runs of one method can differ between Spring versions, so do not depend on it. Make the guarantee explicit instead. This job refuses to start while a previous run is still active:
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ExportJob {
private static final Logger log = LoggerFactory.getLogger(ExportJob.class);
private final AtomicBoolean running = new AtomicBoolean(false);
@Scheduled(fixedRate = 60000)
public void export() {
if (!running.compareAndSet(false, true)) {
log.warn("previous export still running, skipping this run");
return;
}
try {
// long call to a remote system
} finally {
running.set(false);
}
}
}This guard works within one JVM only. For several instances, see the multi-instance chapter.
Limiting concurrency
An unbounded scheduler can start an unbounded number of threads. Usually that is harmless because each task is short. It becomes a problem when the threads hold a scarce resource such as database connections. A hundred virtual threads waiting on a pool of ten connections just queue at the connection pool, and calls time out.
To cap the number of simultaneous task executions:
spring:
threads:
virtual:
enabled: true
task:
scheduling:
simple:
concurrency-limit: 8When the limit is reached, further executions wait until a slot frees up. The scheduler's trigger thread can block while it waits, so keep the limit comfortably above the number of jobs that can legitimately run at once. A limit smaller than your job count brings back the head-of-line delays you were trying to avoid.
Pinning
A virtual thread is pinned when it cannot unmount while blocked. On Java 21 through 23, blocking inside a synchronized block or method pins the virtual thread to its carrier. Native frames, such as a blocking call made through JNI, pin it as well. A pinned task holds a carrier thread for as long as it waits.
A few pinned tasks cost little. Many pinned tasks can use up all carriers, and then unrelated virtual threads stall, including other scheduled jobs. Java 24 removed the synchronized case (JEP 491).
To find pinning on Java 21, start the application with this option:
-Djdk.tracePinnedThreads=fullThe JVM prints a stack trace whenever a virtual thread blocks while pinned. Common sources are older JDBC drivers and libraries that use synchronized around I/O. Upgrading the library, or moving to a newer Java version, is the fix. Wrapping the code in a ReentrantLock helps only when you own that code.
Shutdown behavior
Virtual threads are daemon threads, so the JVM does not wait for them when it exits. Without a shutdown wait, a running job can be cut off mid-way. Keep the graceful shutdown settings from the shutdown chapter:
spring:
task:
scheduling:
shutdown:
await-termination: true
await-termination-period: 30sRecent Boot versions apply these settings to the virtual-thread scheduler too. Confirm this on your version by starting a task that sleeps for 20 seconds, stopping the application, and checking that the task logs its completion.
Error handling and tests stay the same
Exceptions behave as in the error handling chapter. An exception thrown from a fixedRate, fixedDelay, or cron method is logged by the scheduler's default error handler, and later runs still happen. A custom TaskScheduler or error handler still applies if you define one. Tests that call the scheduled method directly, or that use Awaitility against the running context, need no changes. A test that asserts the executing thread's name or type is the one exception.
When not to use virtual threads
Stay on the platform-thread pool when:
- The tasks are CPU-bound. Virtual threads add no capacity, and an explicit pool sized to the core count gives a hard bound.
- You need strict single-threaded execution across all jobs. The default pool of size 1 provides that. The virtual scheduler does not.
- You depend on a library that pins heavily and you cannot upgrade it.
- You use a custom
TaskSchedulerwith specific settings such as a rejection policy or a metrics-instrumented pool.
Using virtual threads fits best when most jobs wait on network or disk and you have many of them, such as polling several remote APIs, sending notifications, or syncing data between systems.
Summary of decisions
- Check Java 21 or later and Boot 3.2 or later.
- Set
spring.threads.virtual.enabled=true. - Log
Thread.currentThread().isVirtual()from one job to confirm. - Add an explicit overlap guard to jobs that must not run twice at once.
- Set
spring.task.scheduling.simple.concurrency-limitif tasks share a scarce resource. - Keep the shutdown wait settings.
Exercise
You enable spring.threads.virtual.enabled=true and keep spring.task.scheduling.pool.size: 4 in your configuration. Two jobs now corrupt shared data that worked before when run on the default scheduler. Why did the setting not protect you, and what are two fixes?
Show answer
The pool-size property is ignored once Boot uses the virtual-thread SimpleAsyncTaskScheduler, which starts a new virtual thread for each execution. So jobs run concurrently where they were previously serialized by the small pool. Fixes: make the shared data access safe with a lock, transaction, or atomic operation, or add an overlap guard such as an AtomicBoolean for the same job. You could also set spring.task.scheduling.simple.concurrency-limit: 1 to serialize executions, or turn virtual threads off for the scheduler.
Exercise
A scheduled job calls a legacy library that does blocking I/O inside a synchronized method. On Java 21 you see all your jobs stall under load, although CPU use is low. What is the likely cause, and how do you confirm it?
Show answer
The virtual threads are pinned to their carrier threads while blocked inside synchronized, so the few carrier threads are all occupied and other virtual threads cannot run. Confirm it by starting the JVM with -Djdk.tracePinnedThreads=full and looking for the pinned stack traces. Fix it by upgrading the library, replacing the synchronized with a ReentrantLock if you own the code, or moving to Java 24 or later.