CKTIS / Java
Virtual threads in Java
Virtual threads in Java: A Java 21 virtual thread is a lightweight Thread implementation scheduled by the JVM for very large numbers of concurrent, mostly blocking tasks.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
virtual threadsA Java 21 virtual thread is a lightweight Thread implementation scheduled by the JVM for very large numbers of concurrent, mostly blocking tasks.
Run one request task with Thread.ofVirtual or newVirtualThreadPerTaskExecutor and retain straightforward synchronous code for I/O operations.
Virtual threads do not accelerate CPU work and should not be pooled; long synchronized regions or native code can pin a carrier and limit scaling.
A ThreadLocal multiplied across a million threads consumes memory, scheduling order is not guaranteed, and scarce resources still need a semaphore or another limit.
The three Future values are read in order as true:1, true:4, true:9, proving that every task ran on a virtual thread.
Examples
import java.util.*; import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
try(var executor=Executors.newVirtualThreadPerTaskExecutor()) {
var futures=new ArrayList<Future<String>>();
for(int n=1;n<=3;n++){int value=n;futures.add(executor.submit(()->Thread.currentThread().isVirtual()+":"+(value*value)));}
for(var future:futures) System.out.println(future.get());
}
}
}
Result
true:1 true:4 true:9
The three Future values are read in order as true:1, true:4, true:9, proving that every task ran on a virtual thread.