Video in progress
What happens when a CPU-heavy task runs for a long time on virtual threads? Does the scheduler forcibly switch it out?
No, the virtual thread scheduler doesn't do time-slicing: a virtual thread frees its carrier only when it blocks or finishes. Heavy computation on as many threads as there are cores can take over all the carriers and raise the latency of the thousands of other IO threads. CPU work has to be moved to a separate, bounded platform pool.
📖 Answer
The OS preempts platform threads: even if one thread computes for 10 seconds, the others still get CPU time. Virtual threads are effectively cooperative: the scheduler is based on a ForkJoinPool, the number of carriers equals the number of cores by default, and a virtual thread steps off its carrier only on a blocking operation (IO, sleep, waiting for a lock).
The situation:
// an 8-core server, Tomcat on virtual threads
@GetMapping("/report/{id}")
Report build(@PathVariable long id) {
var rows = repo.load(id); // IO: the carrier is freed, good
return pdfRenderer.render(rows); // 3 seconds of pure CPU, never blocks
}
If 8 report requests come in at once, all 8 carriers are busy for 3 seconds. During that time, not a single carrier is left for /health and the light endpoints. It looks like pinning, but the cause is different: nothing is blocking, all the carriers are just busy computing.
What I do:
- I send the CPU-heavy part to a separate platform pool with fewer threads than cores, so the carriers stay free for IO:
private final ExecutorService cpuPool = Executors.newFixedThreadPool(
Math.max(1, Runtime.getRuntime().availableProcessors() / 2));
Report build(long id) throws Exception {
var rows = repo.load(id);
return cpuPool.submit(() -> pdfRenderer.render(rows)).get(); // the virtual thread waits, the carrier is free
}
- I put a concurrency limit on heavy endpoints with a
Semaphore; - you can raise
jdk.virtualThreadScheduler.parallelism, but you don't get more cores, you just bring back OS-level switching, that's all.
Diagnosis: in a case like this, jdk.VirtualThreadPinned in JFR is empty, while the carrier threads (ForkJoinPool-1-worker-*) are fully busy in the CPU profile, and the latency of light requests jumps together with the heavy ones. In current JDKs there is no time-slicing for virtual threads, so this is solved by design.
Sign up to mark studied questions and save your progress.