Virtual threads — lightweight threads managed by JVM, not OS (Java 21+).
Key features:
Creating virtual threads:
1// Factory method2Thread vt = Thread.ofVirtual().start(() -> {3 System.out.println("Hello from virtual thread");4});56// ExecutorService7try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {8 IntStream.range(0, 100_000).forEach(i -> {9 executor.submit(() -> {10 Thread.sleep(Duration.ofSeconds(1));11 return i;12 });13 });14}
How it works:
Performance considerations:
Common pitfalls:
When to use:
When NOT to use: