Virtual threads — lightweight threads managed by the JVM, enabling millions of concurrent threads for I/O-bound workloads.
1// Create virtual thread2Thread.startVirtualThread(() -> {3 System.out.println("Hello from virtual thread");4});56// Virtual thread executor7try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {8 IntStream.range(0, 10_000).forEach(i -> {9 executor.submit(() -> {10 Thread.sleep(Duration.ofSeconds(1));11 return i;12 });13 });14}1516// Structured concurrency (Preview)17try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {18 var user = scope.fork(() -> findUser(id));19 var order = scope.fork(() -> fetchOrder(id));20 scope.join();21 return new Response(user.resultNow(), order.resultNow());22}
vs Platform threads:
Gotcha: synchronized pinning
Key benefits: