On this page
Virtual Threads
Lightweight threads in Java 21.
Overview
Lightweight threads in Java 21.
Example
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> System.out.println("Virtual thread"));
}
Common Use Cases
- High-throughput server applications
- Parallel data processing
Pitfalls to Avoid
- Pinning virtual threads with synchronized blocks on JDK 21
- Unbounded thread creation
Related Topics
- ExecutorService
- CompletableFuture
Best Practices
- Understand when to use virtual threads versus simpler alternatives
- Write unit tests covering edge cases and failure paths
- Follow Java conventions and prefer standard library APIs when available
- Profile before optimizing — measure impact in your specific workload