Concurrency

concurrency6VirtualThreadsDemo

Path
pkg7concurrency/concurrency6VirtualThreadsDemo.java
Package
pkg7concurrency
Study order
6
Run
Single-file source launch
Command
java pkg7concurrency/concurrency6VirtualThreadsDemo.java
Example
Java 21 example
Requires
Java 21

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg7concurrency/concurrency6VirtualThreadsDemo.java
1package pkg7concurrency;2 3/*4 * concurrency6VirtualThreadsDemo.java  (Java 21, Project Loom)5 * ------------------------------------------------6 * Virtual threads are lightweight threads scheduled by the JVM onto a small pool7 * of carrier (platform) threads. They make blocking code scale to millions of8 * concurrent tasks — ideal for blocking I/O.9 *10 * PLATFORM vs VIRTUAL:11 *   - Platform thread: 1:1 with an OS thread, ~1MB stack, limited count.12 *   - Virtual thread : cheap (KBs), millions possible; blocks cheaply.13 *14 * WHEN NOT to use: CPU-bound work (no gain). In Java 21, a virtual thread can15 * stay pinned to its carrier inside synchronized. Java 24 (JEP 491) lets it16 * unmount there. This file shows the Java 21 API.17 */18import java.util.concurrent.*;19import java.util.concurrent.atomic.AtomicInteger;20 21public class concurrency6VirtualThreadsDemo {22 23    public static void main(String[] args) throws InterruptedException {24        // 1) Start a single virtual thread25        Thread vt = Thread.ofVirtual().name("vt-demo").start(() ->26                System.out.println("hello from " + Thread.currentThread()));27        vt.join();28        System.out.println("isVirtual: " + vt.isVirtual());29 30        // 2) Launch 100,000 virtual threads, each doing a blocking sleep31        AtomicInteger completed = new AtomicInteger();32        long start = System.currentTimeMillis();33        try (ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor()) {34            for (int i = 0; i < 100_000; i++) {35                exec.submit(() -> {36                    try { Thread.sleep(20); } catch (InterruptedException ignored) {}37                    completed.incrementAndGet();38                });39            }40        }   // close() waits for all tasks to finish41        long elapsed = System.currentTimeMillis() - start;42 43        System.out.println("completed " + completed.get() + " virtual-thread tasks in " + elapsed + "ms");44        System.out.println("(doing this with 100k platform threads would exhaust memory)");45    }46}