Skip to main content
Java 21 (LTS) · Topic 1 of 4

Virtual threads

Definition​

Virtual threads (Java 21) are very cheap threads managed by the JVM. When one waits, for example on a network call, it steps aside so another can run. You can run tens of thousands at once with simple blocking code.

Example code​

10,000 tasks that each wait, run at the same time

import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

class Demo {
public static void main(String[] args) {
AtomicInteger finished = new AtomicInteger();

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { // one virtual thread per task
for (int i = 0; i < 10_000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(100)); // waiting does not block a core
finished.incrementAndGet();
return null;
});
}
} // close() waits for all tasks

System.out.println(finished.get() + " tasks finished");
}
}

// Output:
// 10000 tasks finished

Finished this page? Track your progress (saved only in your browser).