Virtual Threads (Project Loom, Java 21 GA) là thread nhẹ do JVM quản lý — chạy hàng triệu thread trên chỉ vài OS thread.
Vấn đề trước Java 21: Platform Thread = 1:1 với OS thread, ~1MB stack. Server muốn xử lý 10K request đồng thời → 10K OS thread → OOM. Phải chuyển sang async/reactive (CompletableFuture, WebFlux) — code phức tạp, khó debug.
Virtual Thread giải quyết: lịch trình M:N — nhiều virtual thread multiplexed trên ít OS thread (carrier thread). Khi virtual thread block I/O, JVM "park" nó và carrier thread chuyển sang phục vụ virtual thread khác.
// Tạo trực tiếp
Thread.ofVirtual().start(() -> fetchAPI());
// Pattern khuyến nghị — ExecutorService
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
exec.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return fetchFromAPI();
});
}
} // auto-shutdownLợi ích: code đồng bộ đơn giản đạt concurrency cao như reactive.
Không phù hợp: CPU-bound task (bottleneck là tính toán, không phải I/O — Virtual Thread không giúp gì).
Lưu ý 2026: Spring Boot 3.2+ tự động dùng Virtual Threads cho web server nếu enable spring.threads.virtual.enabled=true.
Virtual Threads (Project Loom, Java 21 GA) are lightweight threads managed by the JVM — run millions on just a few OS threads.
The pre-Java 21 problem: Platform Threads are 1:1 with OS threads, ~1MB stack. A server handling 10K concurrent requests → 10K OS threads → OOM. You had to switch to async/reactive (CompletableFuture, WebFlux) — complex, hard to debug.
Virtual Threads fix it: M:N scheduling — many virtual threads multiplexed over few OS (carrier) threads. When a virtual thread blocks on I/O, the JVM "parks" it and the carrier thread serves another virtual thread.
// Direct creation
Thread.ofVirtual().start(() -> fetchAPI());
// Recommended pattern — ExecutorService
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
exec.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return fetchFromAPI();
});
}
} // auto-shutdownBenefits: simple synchronous code with reactive-level concurrency.
Not for: CPU-bound tasks (the bottleneck is compute, not I/O — virtual threads do not help).
2026 note: Spring Boot 3.2+ auto-uses Virtual Threads for its web server with spring.threads.virtual.enabled=true.