Java Virtual Threads: Lightweight, High-Concurrency, and Scalable Concurrency

Traditional threading model in Java: ```java // Each thread = 1 OS thread (~1-2 MB stack) // 1000 threads = 1-2 GB memory just for stacks ExecutorService executor = Executors.newFixedThreadPool(100); for (int i = 0; i < 1000; i++) { executor.submit(() -> { handleRequest(); // Blocks on I/O }); } ``` Thread pools. Limited concurrency. Wasted memory while threads wait. Virtual Threads (Java 21): ```java // Millions of threads possible try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 1000000; i++) { executor.submit(() -> { handleRequest(); // When blocked, virtual thread unmounts }); } } ``` How they work: · Lightweight (few KB, not MB) · Not tied 1:1 to OS threads · When virtual thread blocks on I/O, it's unmounted from carrier thread · Carrier thread can run other virtual threads · No pooling needed. Create as many as you want. Simple creation: ```java // Create and start Thread vThread = Thread.startVirtualThread(() -> { System.out.println("Hello from virtual thread"); }); // Or using builder Thread vThread = Thread.ofVirtual() .name("my-virtual") .unstarted(() -> { /* task */ }); vThread.start(); ``` Where they shine: · High-concurrency servers · Many concurrent I/O operations · Each request gets its own thread (simple synchronous code) Where they DON'T help: · CPU-bound work (still limited by cores) · Already using reactive/async frameworks (may simplify them instead) The biggest change to Java concurrency since... ever. Write simple blocking code at scale. #Java #VirtualThreads #ProjectLoom #Concurrency #Java21 #Performance

  • diagram

To view or add a comment, sign in

Explore content categories