Conceptcore
Virtual threads
Also called Java virtual threads, Project Loom threads, JEP 444, carrier thread, pinned virtual thread, Thread.ofVirtual, newVirtualThreadPerTaskExecutor, user-mode threads.
A virtual thread is a Java thread that the JDK schedules onto a small pool of OS threads. When it blocks, it gives its OS thread to another virtual thread, so a program can run millions.
- Applies to
- core-languages
Idea
A virtual thread is a Java thread that the JDK implements, not the operating system. JEP 444 calls virtual threads "a lightweight implementation of threads that is provided by the JDK rather than the OS".1 The classic Java thread, which is now called a platform thread, is "a thin wrapper around an operating system (OS) thread", and it keeps that OS thread for its whole life.2 A virtual thread runs on an OS thread only while it has work to do. When it blocks, for example on I/O, the JDK suspends it, and the OS thread is free to run other virtual threads.2
Both kinds are instances of java.lang.Thread, so code that uses threads works with both. In the example below, the same method runs on a platform thread and on a virtual thread.
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread platform = Thread.ofPlatform().name("platform-1").start(Main::describe);
platform.join();
Thread virtual = Thread.ofVirtual().name("virtual-1").start(Main::describe);
virtual.join();
}
static void describe() {
Thread current = Thread.currentThread();
System.out.println(current.getName() + ": isVirtual=" + current.isVirtual()
+ ", isDaemon=" + current.isDaemon());
}
}
platform-1: isVirtual=false, isDaemon=false
virtual-1: isVirtual=true, isDaemon=true
The builder Thread.ofVirtual() makes a virtual thread, and join waits for it as for any thread. A virtual thread is always a daemon thread, so it does not keep the JVM running.3 The purpose of virtual threads is scale. A program can have "a great many active virtual threads, even millions, running in the same Java process".2
How it works
Carriers, mounting and unmounting
The JDK has its own scheduler for virtual threads. It is a work-stealing ForkJoinPool that runs in FIFO mode, and by default it has as many platform threads as there are available processors.1 To run a virtual thread, the scheduler mounts it on one of these platform threads, which becomes its carrier. When the virtual thread blocks, it unmounts, and the carrier is free to run another virtual thread. When the blocking operation is ready, the virtual thread goes back to the scheduler, which mounts it again, maybe on a different carrier.1
virtual threads: V1 V2 V3 V4 ... (many)
\ | | /
scheduler (ForkJoinPool)
/ \
carriers: platform-A platform-B (about one per processor)
| |
OS threads: OS-1 OS-2
This is the M:N model of Green threads: many virtual threads on few OS threads.1 The Oracle guide compares it to virtual memory, which maps a large address space to a limited amount of RAM.2 From the point of view of Java code, the carrier is invisible: Thread.currentThread() always gives the virtual thread itself.1
Blocking calls
The JDK changes its blocking operations so that they unmount the virtual thread instead of blocking the carrier. A virtual thread will typically unmount "when it blocks on I/O or some other blocking operation in the JDK".1 So code can use the plain blocking style. Each request can have its own thread, as in the thread-per-request style, which JEP 444 calls "easy to understand, easy to program".1
Pinning
Sometimes a virtual thread cannot unmount. It is then pinned to its carrier, and a blocking operation blocks the carrier and its OS thread too.1 In JDK 21, a virtual thread was pinned in two cases: in a synchronized block or method, and in a native method or a foreign function.1 JEP 491 in JDK 24 removed the first case for nearly all code. It lets a virtual thread that blocks in synchronized code release its platform thread.4 A virtual thread is still pinned when it calls native code that calls back into Java code that blocks.4 Pinning does not make a program wrong, but it "might hinder its scalability".1
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Absent | |
| C++ | Absent | |
| Java | Standard library | |
| C | Absent | C threads are OS threads; no separate example file. Alternative: A fixed set of OS threads, as in the C++ example. |
| C# | Absent | |
| JavaScript | Absent | |
| TypeScript | Absent | TypeScript runs on a JavaScript engine, which has no virtual threads. No example file exists. Alternative: Async functions on the event loop, as in the JavaScript example. |
| Go | Native | |
| Rust | Absent | |
| Kotlin | Standard library | On the JVM, Kotlin uses the Java virtual threads, as in the Java example; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | A query does not start threads. |
| Bash | Absent | Bash has no threads. No example file exists. Alternative: Background processes with & and wait. |
| PowerShell | Absent | Thread jobs run on OS threads; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: Start-ThreadJob with -ThrottleLimit. |
| HTML | Does not apply | Markup has no threads. |
| CSS | Does not apply | Style rules have no threads. |
| Regular expressions | Does not apply | A pattern has no threads. |
Virtual threads are a feature of the Java platform. Other languages solve the same problem, many tasks that spend most of their time waiting, with goroutines, async tasks or a pool of OS threads. The example files run 1,000 tasks that each wait 10 ms, and allow at most 10 of them to run at the same time. The table gives the verdict for each tier 1 language.
| Language | Verdict | Mechanism |
|---|---|---|
| Python | absent | asyncio tasks instead |
| JavaScript | absent | async functions on the event loop instead |
| TypeScript | absent | as JavaScript |
| Java | stdlib | Thread.ofVirtual(), Executors.newVirtualThreadPerTaskExecutor() (Java 21) |
| Kotlin | stdlib | the Java virtual threads on the JVM |
| C# | absent | async methods and tasks instead |
| Go | native | goroutines are M:N threads of the Go runtime |
| Rust | absent | a fixed set of OS threads, or async tasks with a library executor |
| C | absent | a pool of OS threads |
| C++ | absent | a pool of OS threads |
| Bash | absent | background processes |
| PowerShell | absent | thread jobs on OS threads |
| SQL | n/a | a query does not start threads |
| Regex | n/a | a pattern has no threads |
| HTML/CSS | n/a | markup and style rules have no threads |
- Java.
Thread.ofVirtual()returns a builder for virtual threads, andThread.startVirtualThread(Runnable)creates and starts one.1 Virtual threads are "not intended for long running CPU intensive operations".3 - Go. JEP 444 names goroutines in Go and processes in Erlang as user-mode threads that "have been successful in other multithreaded languages".1 The Go FAQ says that it is "practical to create hundreds of thousands of goroutines in the same address space".5
- C#, Python and JavaScript. These languages have no virtual threads. An
asyncfunction gives its thread back at eachawait, so many waiting tasks need few threads. Unlike a virtual thread, anasyncfunction must mark each point where it can wait.
import asyncio
TASKS = 1_000
async def main():
permits = asyncio.Semaphore(10)
active = 0
peak = 0
async def work(n):
nonlocal active, peak
async with permits:
active += 1
peak = max(peak, active)
await asyncio.sleep(0.01) # the task gives the event loop back here
active -= 1
return n
results = await asyncio.gather(*(work(n) for n in range(TASKS)))
print(f"tasks: {len(results)}, sum: {sum(results)}")
print(f"never more than 10 at once: {peak <= 10}")
asyncio.run(main())
tasks: 1000, sum: 499500
never more than 10 at once: True
- Verdict: absent. Python has no virtual threads.
asynciotasks are the alternative: many tasks share one thread, and eachawaitis a point where a task can wait. asyncio.Semaphore(10)lets at most ten tasks into theasync withblock at the same time.- All tasks run on one thread, so
activeandpeakneed no lock. - A blocking call, for example
time.sleep, inside a task stops every task on the event loop.
#include <atomic>
#include <chrono>
#include <cstdint>
#include <iostream>
#include <thread>
#include <vector>
int main() {
constexpr int kTasks = 1000;
constexpr int kWorkers = 10;
std::atomic<int> next{0};
std::atomic<std::int64_t> sum{0};
{
// Ten OS threads take tasks from a shared counter until none are left.
std::vector<std::jthread> workers;
for (int w = 0; w < kWorkers; ++w) {
workers.emplace_back([&] {
for (int n = next.fetch_add(1); n < kTasks; n = next.fetch_add(1)) {
std::this_thread::sleep_for(std::chrono::milliseconds(10)); // blocks this OS thread
sum += n;
}
});
}
} // each jthread joins here
std::cout << "tasks: " << kTasks << ", sum: " << sum << '\n';
std::cout << "OS threads: " << kWorkers << ", so never more than " << kWorkers << " at once\n";
}
tasks: 1000, sum: 499500
OS threads: 10, so never more than 10 at once
- Verdict: absent. A
std::threadorstd::jthreadis an OS thread, and the standard library has no M:N scheduler. A fixed set of OS threads is the usual alternative. - Ten threads take task numbers from an atomic counter. The limit of ten comes from the number of threads.
sleep_forblocks the whole OS thread, so the threads cannot run other tasks while they wait.- The vector of
std::jthreadobjects goes out of scope at the end of the inner block, and each destructor joins its thread beforemainreads the sum.
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class Main {
public static void main(String[] args) {
final int tasks = 1_000;
final Semaphore permits = new Semaphore(10);
final AtomicInteger active = new AtomicInteger();
final AtomicInteger peak = new AtomicInteger();
final AtomicLong sum = new AtomicLong();
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < tasks; i++) {
final int n = i;
executor.submit(() -> {
permits.acquire();
try {
peak.accumulateAndGet(active.incrementAndGet(), Math::max);
Thread.sleep(Duration.ofMillis(10)); // the virtual thread unmounts here
sum.addAndGet(n);
active.decrementAndGet();
} finally {
permits.release();
}
return null;
});
}
} // close() waits for every task
System.out.println("tasks: " + tasks + ", sum: " + sum.get());
System.out.println("never more than 10 at once: " + (peak.get() <= 10));
}
}
tasks: 1000, sum: 499500
never more than 10 at once: true
- Verdict: stdlib. Java 21 has virtual threads.
newVirtualThreadPerTaskExecutorstarts a new virtual thread for each task, and closing the executor waits for all of them. - The executor creates 1,000 virtual threads, one for each task, and does not pool them. A
Semaphorewith 10 permits limits how many tasks wait at the same time. - While a virtual thread sleeps, it unmounts, and its carrier runs other virtual threads.
- The
tryblock withfinallyreleases the permit even if the task fails.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
const int Tasks = 1_000;
var permits = new SemaphoreSlim(10);
int active = 0;
int peak = 0;
async Task<int> Work(int n)
{
await permits.WaitAsync();
try
{
int now = Interlocked.Increment(ref active);
int old;
while (now > (old = Volatile.Read(ref peak)) && Interlocked.CompareExchange(ref peak, now, old) != old)
{
}
await Task.Delay(10); // no thread is held while the task waits
Interlocked.Decrement(ref active);
return n;
}
finally
{
permits.Release();
}
}
int[] results = await Task.WhenAll(Enumerable.Range(0, Tasks).Select(Work));
Console.WriteLine($"tasks: {results.Length}, sum: {results.Sum()}");
Console.WriteLine($"never more than 10 at once: {Volatile.Read(ref peak) <= 10}");
tasks: 1000, sum: 499500
never more than 10 at once: True
- Verdict: absent. .NET has no virtual threads.
asyncmethods are the alternative: at eachawait, the method gives its pool thread back until the awaited operation completes. SemaphoreSlim.WaitAsyncwaits for a permit without a blocked thread. Ten permits allow at most ten tasks in the delay at the same time.- The 1,000 tasks need only a few pool threads, because a task holds no thread while it waits.
- Unlike a virtual thread, an
asyncmethod must mark each point where it can wait withawait.
const TASKS = 1_000;
const LIMIT = 10;
let active = 0;
let peak = 0;
const waiting = [];
// A small semaphore: acquire resolves when a permit is free.
function acquire() {
if (active < LIMIT) {
active++;
return Promise.resolve();
}
return new Promise((resolve) => waiting.push(resolve));
}
function release() {
const next = waiting.shift();
if (next) {
next(); // pass the permit on; active stays the same
} else {
active--;
}
}
async function work(n) {
await acquire();
try {
peak = Math.max(peak, active);
await new Promise((resolve) => setTimeout(resolve, 10));
return n;
} finally {
release();
}
}
const results = await Promise.all(Array.from({ length: TASKS }, (_, n) => work(n)));
console.log(`tasks: ${results.length}, sum: ${results.reduce((a, b) => a + b, 0)}`);
console.log(`never more than 10 at once: ${peak <= LIMIT}`);
tasks: 1000, sum: 499500
never more than 10 at once: true
- Verdict: absent. JavaScript has no virtual threads.
asyncfunctions on the event loop are the alternative: one thread runs all of them, and eachawaitlets another function run. - The standard library has no semaphore, so the example writes a small one.
acquirewaits when ten tasks are active, andreleasepasses the permit to the next waiting task. - All tasks run on one thread, so the counters need no lock.
Promise.allwaits for all tasks and keeps the results in order.
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
const tasks = 1_000
permits := make(chan struct{}, 10) // a buffered channel used as a semaphore
var active, peak, sum atomic.Int64
var wg sync.WaitGroup
for i := range tasks {
wg.Add(1)
go func() {
defer wg.Done()
permits <- struct{}{}
defer func() { <-permits }()
now := active.Add(1)
for {
old := peak.Load()
if now <= old || peak.CompareAndSwap(old, now) {
break
}
}
time.Sleep(10 * time.Millisecond)
sum.Add(int64(i))
active.Add(-1)
}()
}
wg.Wait()
fmt.Printf("tasks: %d, sum: %d\n", tasks, sum.Load())
fmt.Println("never more than 10 at once:", peak.Load() <= 10)
}
tasks: 1000, sum: 499500
never more than 10 at once: true
- Verdict: native. Go has no type called a virtual thread, but goroutines are the same idea: the runtime schedules many goroutines onto a few OS threads.
- The program starts one goroutine for each task. A buffered channel with room for 10 values acts as the semaphore: a send takes a permit and a receive gives it back.
- A goroutine that waits on the full channel or in
time.Sleepdoes not hold an OS thread. - The loop with
CompareAndSwapkeeps the largest number of active tasks that any goroutine has seen.
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;
const TASKS: usize = 1_000;
const WORKERS: usize = 10;
fn main() {
let next = AtomicUsize::new(0);
let sum = AtomicU64::new(0);
// Ten OS threads take tasks from a shared counter until none are left.
thread::scope(|s| {
for _ in 0..WORKERS {
s.spawn(|| loop {
let n = next.fetch_add(1, Ordering::Relaxed);
if n >= TASKS {
break;
}
thread::sleep(Duration::from_millis(10)); // blocks this OS thread
sum.fetch_add(n as u64, Ordering::Relaxed);
});
}
});
println!("tasks: {TASKS}, sum: {}", sum.load(Ordering::Relaxed));
println!("OS threads: {WORKERS}, so never more than {WORKERS} at once");
}
tasks: 1000, sum: 499500
OS threads: 10, so never more than 10 at once
- Verdict: absent. A Rust thread is an OS thread, and the standard library has no M:N scheduler. The two alternatives are a fixed set of OS threads, as here, and
asynctasks with an executor from a library. - Ten scoped threads take task numbers from an atomic counter. The limit of ten comes from the number of threads, so the program needs no semaphore.
thread::sleepblocks the whole OS thread. With ten threads, the 1,000 waits of 10 ms take about one second in total.thread::scopejoins the ten threads beforemainreads the sum.
Variations and related ideas
- Green threads. The green threads of early Java shared one OS thread, and a blocking call blocked them all. Virtual threads differ: they live next to platform threads, and "sleeping on a virtual thread does not block the underlying carrier thread".6
- Thread pool. A pool shares a few expensive platform threads among many tasks. Virtual threads are cheap, so "there is never a need to pool them".1 The JEP recommends a new virtual thread for each task.1
- Semaphores to limit concurrency. Programs sometimes use a pool of fixed size to limit how many tasks use a resource at the same time. With virtual threads, the JEP recommends constructs made for this purpose, "such as semaphores".1 The example files use this approach.
- Futures and promises and
asynccode. An asynchronous API returns at once and completes a future later. Virtual threads give the same scale with blocking code, so a stack trace and a debugger show one task on one thread.1
Pitfalls
- CPU-bound work. Virtual threads "do not run code any faster than platform threads". They give throughput when there are many tasks that wait, not lower latency for one task.1 A long computation keeps its carrier busy.3
- Pooling virtual threads. A pool of virtual threads brings back the limits that virtual threads remove. Create a new virtual thread for each task.1
- Pinning on old JDKs. On JDK 21 to 23, a virtual thread that blocks inside
synchronizedcode holds its carrier.14 Frequent, long pinning "can harm the scalability of an application by capturing carriers".1 The system propertyjdk.tracePinnedThreadsprints a stack trace when a thread blocks while pinned.1 - Thread-local variables. Virtual threads support them, but a single JVM can have millions of virtual threads, so a large value in each thread-local variable adds up.2
Cost
- Memory. A virtual thread typically has a shallow call stack and needs few resources.23 A platform thread has a large stack and other resources that the operating system keeps.2
- Speed. A virtual thread runs code at the same speed as a platform thread.1 The gain is in the number of threads, not in the speed of each.
- Scheduling. Mounting and unmounting happen often and do not block platform threads.4
History
Java first had threads in user mode: the green threads of early Java.1 Later versions changed to OS threads. Virtual threads came as a preview in JDK 19 (JEP 425) and JDK 20 (JEP 436), and JEP 444, created in 2023, made them final in JDK 21.1 JEP 491, delivered in JDK 24, removed pinning in synchronized code for nearly all cases.4
References
- JEP 444: Virtual Threads, Summary; History; Goals; Motivation; Description; Do not pool virtual threads
- Java SE 21 Core Libraries, Virtual Threads, What is a Platform Thread?; What is a Virtual Thread?
- Java SE 21 API, java.lang.Thread, Virtual threads
- JEP 491: Synchronize Virtual Threads without Pinning, Summary; Description
- Go FAQ, Why goroutines instead of threads?
- Wikipedia, Green thread, Differences to virtual threads in the Java Virtual Machine
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag R4Y8QZ Edit this page History Report an error Markdown