Lab 03: Project Loom — Virtual Threads
Overview
Step 1: Virtual Thread Basics
// Three ways to create virtual threads in Java 21
public class VirtualThreadBasics {
public static void main(String[] args) throws Exception {
// 1. Thread.ofVirtual()
Thread vt1 = Thread.ofVirtual()
.name("my-vthread")
.start(() -> System.out.println("Running in: " + Thread.currentThread()));
vt1.join();
// 2. Thread.startVirtualThread()
Thread vt2 = Thread.startVirtualThread(() ->
System.out.println("Virtual: " + Thread.currentThread().isVirtual())
);
vt2.join();
// 3. Executor (preferred for pools)
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
exec.submit(() -> System.out.println("Via executor"));
}
System.out.println("Is virtual: " + vt1.isVirtual());
System.out.println("Is daemon: " + vt1.isDaemon()); // always true
}
}Step 2: Carrier Threads and Mounting/Unmounting
Step 3: 10000 Virtual Threads Benchmark
Step 4: Thread Locals vs ScopedValues
Step 5: Structured Concurrency Pattern (Manual)
Step 6: Virtual Thread Pinning and Diagnostics
Step 7: Virtual Threads with HTTP (Conceptual)
Step 8: Capstone — Full Virtual Thread Demo
Summary
Concept
API
Key Benefit
Last updated
