6 · Advanced · lesson 37 of 41
Virtual Threads (Project Loom)
Millions of cheap threads scheduled on a few carriers (Java 21+).
Java
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1_000_000; i++) {
exec.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return null;
});
}
}NOTE
Virtual threads are managed by the JVM, not the OS. Blocking is nearly free.
Loading 3D scene…
Key takeaways
- ✓Write blocking code; the JVM parks/unparks the virtual thread.
- ✓Great fit for I/O-heavy servers.