Virtual threads in Java 21 enable millions of concurrent threads without the overhead of platform threads.
Virtual Threads¶
// Creating a virtual thread Thread.startVirtualThread(() -> { var result = fetchFromDB(); process(result); }); // ExecutorService with virtual threads try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { List> futures = urls.stream() .map(url -> executor.submit(() -> fetch(url))) .toList(); for (var future : futures) { System.out.println(future.get()); } }
Spring Boot Integration¶
Java 21 Virtual Threads¶
spring.threads.virtual.enabled=true
All request handlers run on virtual threads!¶
When to Use¶
- I/O-bound operations (HTTP, DB, file)
- High number of concurrent requests
- NOT for CPU-bound operations
- NOT for synchronized blocks (pinning)
Key Takeaway¶
Virtual threads = millions of concurrent threads. spring.threads.virtual.enabled=true and you’re done. Watch out for synchronized.