Virtual threads

suggest change

A virtual thread (final in Java 21, JEP 444) is a java.lang.Thread that the JVM schedules itself, instead of mapping it one-to-one onto an operating system thread. When a virtual thread blocks, for example in Thread.sleep, a socket read, a BlockingQueue.take or a JDBC call, the JVM unmounts it from the OS thread it was running on and runs another virtual thread there. When the blocking operation finishes, the virtual thread is mounted again, possibly on a different OS thread, and continues.

Some terms:

The point of virtual threads is to let you write simple blocking code, one thread per request or per task, and still handle as many concurrent tasks as asynchronous code would. They are not faster threads: a virtual thread runs code at the same speed as a platform thread.

Creating virtual threads

There are several ways to create a virtual thread. All of them return an ordinary Thread:

public class Basics {
    public static void main(String[] args) throws InterruptedException {
        // 1. builder: unstarted or started
        Thread t1 = Thread.ofVirtual().name("worker-1").start(() ->
            System.out.println("hello from " + Thread.currentThread()));
        t1.join();

        // 2. shortcut
        Thread t2 = Thread.startVirtualThread(() ->
            System.out.println("isVirtual: " + Thread.currentThread().isVirtual()));
        t2.join();

        // 3. a builder with a numbered name can make many threads
        Thread.Builder builder = Thread.ofVirtual().name("job-", 0);
        Thread a = builder.start(() -> System.out.println(Thread.currentThread().getName()));
        Thread b = builder.start(() -> System.out.println(Thread.currentThread().getName()));
        a.join();
        b.join();

        // 4. unstarted thread
        Thread t3 = Thread.ofVirtual().unstarted(() -> System.out.println("started later"));
        System.out.println("state before start: " + t3.getState());
        t3.start();
        t3.join();

        System.out.println("daemon: " + t3.isDaemon() + ", priority: " + t3.getPriority());
        System.out.println("main is virtual: " + Thread.currentThread().isVirtual());
    }
}
hello from VirtualThread[#36,worker-1]/runnable@ForkJoinPool-1-worker-1
isVirtual: true
job-0
job-1
state before start: NEW
started later
daemon: true, priority: 5
main is virtual: false

Things to notice:

new Thread(...) and subclasses of Thread always create platform threads.

The virtual-thread-per-task executor

In practice you'll rarely create virtual threads by hand. Executors.newVirtualThreadPerTaskExecutor() returns an ExecutorService that starts a new virtual thread for every task you submit. It works with all the existing Future and invokeAll code (see Callable and Future), and since Java 19 ExecutorService is AutoCloseable: close() waits for all submitted tasks to finish.

Here are 10,000 tasks that each block for 100 ms, run on a fixed pool of 200 platform threads and then on virtual threads:

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

public class ManyTasks {
    static final int TASKS = 10_000;

    public static void main(String[] args) {
        run("fixed pool of 200 platform threads", Executors.newFixedThreadPool(200));
        run("virtual thread per task", Executors.newVirtualThreadPerTaskExecutor());
    }

    static void run(String label, ExecutorService executor) {
        AtomicInteger done = new AtomicInteger();
        long start = System.nanoTime();
        try (executor) {   // close() waits for all tasks to finish
            for (int i = 0; i < TASKS; i++) {
                executor.submit(() -> {
                    Thread.sleep(Duration.ofMillis(100));   // stands in for a blocking call
                    return done.incrementAndGet();
                });
            }
        }
        long ms = (System.nanoTime() - start) / 1_000_000;
        System.out.printf("%-36s %d tasks in %5d ms%n", label, done.get(), ms);
    }
}
fixed pool of 200 platform threads   10000 tasks in  5230 ms
virtual thread per task              10000 tasks in   200 ms

The pool can only have 200 tasks sleeping at once, so it needs 50 rounds of 100 ms. With virtual threads all 10,000 sleep at the same time on a couple dozen carrier threads.

To name the threads, pass a factory from the builder to Executors.newThreadPerTaskExecutor:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Named {
    public static void main(String[] args) {
        ThreadFactory factory = Thread.ofVirtual().name("fetcher-", 1).factory();
        try (ExecutorService executor = Executors.newThreadPerTaskExecutor(factory)) {
            for (int i = 0; i < 3; i++) {
                executor.submit(() -> System.out.println("running in " + Thread.currentThread().getName()));
            }
        }
    }
}
running in fetcher-2
running in fetcher-3
running in fetcher-1

A million threads

Because a blocked virtual thread is just an object on the heap, you can start far more of them than the OS would ever allow for platform threads:

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class Million {
    public static void main(String[] args) throws InterruptedException {
        long start = System.nanoTime();
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 1_000_000; i++) {
            threads.add(Thread.startVirtualThread(() -> {
                try {
                    Thread.sleep(Duration.ofSeconds(1));
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }));
        }
        for (Thread t : threads) {
            t.join();
        }
        long ms = (System.nanoTime() - start) / 1_000_000;
        System.out.println(threads.size() + " virtual threads finished in " + ms + " ms");
    }
}
1000000 virtual threads finished in 7777 ms

Most of the time goes into creating, scheduling and collecting a million threads, but it works with the default heap. The same loop with Thread.ofPlatform() fails with OutOfMemoryError: unable to create native thread or brings the machine to a crawl long before a million.

Where virtual threads help: blocking I/O

Virtual threads shine when tasks spend most of their time waiting: calling HTTP services, querying databases, reading files or sockets. This program starts a deliberately slow local HTTP server (every response takes 200 ms) and calls it 500 times with the ordinary, blocking HttpClient.send:

import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class HttpFanOut {
    public static void main(String[] args) throws Exception {
        // A slow local server: every request takes 200 ms.
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 1000);
        server.createContext("/item", exchange -> {
            try { Thread.sleep(200); } catch (InterruptedException e) { }
            byte[] body = exchange.getRequestURI().getQuery().getBytes();
            exchange.sendResponseHeaders(200, body.length);
            exchange.getResponseBody().write(body);
            exchange.close();
        });
        server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
        server.start();
        int port = server.getAddress().getPort();

        try {
            fetchAll(port);
        } finally {
            server.stop(0);
        }
    }

    static void fetchAll(int port) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        long start = System.nanoTime();
        List<Future<String>> results = new ArrayList<>();
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 500; i++) {
                URI uri = URI.create("http://127.0.0.1:" + port + "/item?id=" + i);
                results.add(executor.submit(() -> {
                    // plain blocking call: the virtual thread is parked while it waits
                    HttpRequest req = HttpRequest.newBuilder(uri).build();
                    return client.send(req, HttpResponse.BodyHandlers.ofString()).body();
                }));
            }
        }
        long ms = (System.nanoTime() - start) / 1_000_000;
        System.out.println("first: " + results.getFirst().get() + ", last: " + results.getLast().get());
        System.out.println(results.size() + " requests in " + ms + " ms");
    }
}
first: id=0, last: id=499
500 requests in 639 ms

500 sequential requests would take 100 seconds. Both sides use virtual threads here: the server handles each request on its own virtual thread (server.setExecutor(...)), and the client sends each request from its own. The code is straightforward blocking code with no callbacks or CompletableFuture chains, and stack traces and debuggers work as usual.

The second argument to HttpServer.create is the accept backlog. With the default, the OS refused some of the 500 simultaneous connections: once threads are cheap, other limits (backlogs, file handles, connection pools, the remote service) are what you hit first.

The same applies to frameworks: Spring Boot (spring.threads.virtual.enabled=true), Helidon, Quarkus, Tomcat and Jetty can all run request handlers on virtual threads.

Where they don't help: CPU-bound work

A virtual thread only frees its carrier when it blocks. Code that computes without blocking keeps its carrier busy, and there are only as many carriers as CPU cores. So for CPU-bound work, virtual threads give the same throughput as a fixed pool sized to the number of cores:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CpuBound {
    // deliberately slow: counts primes below n by trial division
    static long countPrimes(int n) {
        long count = 0;
        for (int i = 2; i < n; i++) {
            boolean prime = true;
            for (int d = 2; (long) d * d <= i; d++) {
                if (i % d == 0) { prime = false; break; }
            }
            if (prime) count++;
        }
        return count;
    }

    public static void main(String[] args) throws Exception {
        int cpus = Runtime.getRuntime().availableProcessors();
        System.out.println("CPUs: " + cpus);
        for (int round = 0; round < 2; round++) {   // round 0 warms up the JIT
            time("fixed pool, " + cpus + " threads", Executors.newFixedThreadPool(cpus), round);
            time("virtual thread per task", Executors.newVirtualThreadPerTaskExecutor(), round);
        }
    }

    static void time(String label, ExecutorService executor, int round) throws Exception {
        long start = System.nanoTime();
        long total = 0;
        try (executor) {
            List<Future<Long>> futures = new ArrayList<>();
            for (int i = 0; i < 200; i++) {
                futures.add(executor.submit(() -> countPrimes(300_000)));
            }
            for (Future<Long> f : futures) total += f.get();
        }
        long ms = (System.nanoTime() - start) / 1_000_000;
        if (round == 1) System.out.printf("%-26s %d ms (total %d)%n", label, ms, total);
    }
}
CPUs: 24
fixed pool, 24 threads     560 ms (total 5199400)
virtual thread per task    493 ms (total 5199400)

The two are about the same. For computation, use a fixed pool, ForkJoinPool or parallel streams. The virtual thread scheduler is also not time-sliced: a virtual thread that loops for a long time without blocking doesn't yield its carrier to other virtual threads, so a few long CPU-bound tasks can delay many I/O-bound ones that share the same carriers.

Don't pool virtual threads; limit concurrency with a Semaphore

Thread pools exist because platform threads are expensive. Virtual threads are cheap, so never put them in a pool: create a new one per task and let it die. A pool of virtual threads only adds a queue and gives nothing back.

Fixed-size pools often had a second, hidden job: limiting how many tasks hit some resource at once. With a pool of 10 threads, at most 10 calls go to the database. With a virtual thread per task that limit is gone, so make it explicit with a Semaphore:

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;

public class Limit {
    // at most 10 calls to the rate-limited service at a time
    static final Semaphore permits = new Semaphore(10);
    static final AtomicInteger inFlight = new AtomicInteger();
    static final AtomicInteger maxInFlight = new AtomicInteger();

    static String callService(int id) throws InterruptedException {
        permits.acquire();
        try {
            int now = inFlight.incrementAndGet();
            maxInFlight.accumulateAndGet(now, Math::max);
            Thread.sleep(Duration.ofMillis(50));   // the remote call
            return "result " + id;
        } finally {
            inFlight.decrementAndGet();
            permits.release();
        }
    }

    public static void main(String[] args) {
        long start = System.nanoTime();
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 1000; i++) {
                int id = i;
                executor.submit(() -> callService(id));
            }
        }
        long ms = (System.nanoTime() - start) / 1_000_000;
        System.out.println("max concurrent calls: " + maxInFlight.get());
        System.out.println("1000 calls in " + ms + " ms");
    }
}
max concurrent calls: 10
1000 calls in 5135 ms

All 1000 virtual threads start right away, but the 990 that can't get a permit wait in acquire(), which costs nothing but a little heap. A database connection pool does the same job for database work; see Database connection pooling, which shows a thousand virtual threads sharing ten connections.

Pinning

A virtual thread is pinned when it blocks but the JVM can't unmount it, so its carrier is blocked too. A few pinned threads are harmless; many of them can use up all the carriers and stall every other virtual thread.

Before JDK 24, the main cause was synchronized: a virtual thread that blocked inside a synchronized block or method, or in Object.wait(), stayed pinned. The usual advice was to replace synchronized with ReentrantLock around blocking calls. Since JDK 24 (JEP 491) virtual threads can block, wait and acquire monitors inside synchronized without pinning, so that advice is obsolete. This program runs 1000 tasks that each sleep 100 ms while holding a monitor, on only 4 carriers:

import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Pinning {
    static void sleep(long ms) {
        try {
            Thread.sleep(Duration.ofMillis(ms));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) {
        long start = System.nanoTime();
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 1000; i++) {
                Object lock = new Object();
                executor.submit(() -> {
                    synchronized (lock) {
                        sleep(100);   // blocking while holding a monitor
                    }
                });
            }
        }
        long ms = (System.nanoTime() - start) / 1_000_000;
        System.out.println("1000 synchronized sleeps of 100 ms took " + ms + " ms");
    }
}
$ java -Djdk.virtualThreadScheduler.parallelism=4 Pinning.java
1000 synchronized sleeps of 100 ms took 134 ms

On JDK 25 all 1000 threads sleep at once. On JDK 21 each sleeping thread would pin one of the 4 carriers, so the tasks would run 4 at a time and take about 1000 / 4 × 100 ms = 25 seconds.

Pinning still happens in a few cases on JDK 25:

The JDK reports pinning as the JFR event jdk.VirtualThreadPinned, recorded by default when the thread stays pinned for more than 20 ms. Here a static initializer sleeps:

import java.time.Duration;

public class ClassInitPin {
    static class Config {
        static final String VALUE;
        static {
            try {
                Thread.sleep(Duration.ofMillis(50));   // e.g. reading a file in a static initializer
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            VALUE = "loaded";
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = Thread.startVirtualThread(() -> System.out.println(Config.VALUE));
        t.join();
    }
}
$ java -XX:StartFlightRecording:filename=pin.jfr,settings=default ClassInitPin.java
loaded
$ jfr print --events jdk.VirtualThreadPinned pin.jfr
jdk.VirtualThreadPinned {
  startTime = 00:21:13.124 (2026-10-18)
  duration = 49.8 ms
  blockingOperation = "LockSupport.park"
  pinnedReason = "VM call to ClassInitPin$Config.<clinit> on stack"
  carrierThread = "ForkJoinPool-1-worker-1" (javaThreadId = 41)
  eventThread = "" (javaThreadId = 40, virtual)
  stackTrace = [
    java.lang.VirtualThread.parkOnCarrierThread(boolean, long) line: 833
    java.lang.VirtualThread.parkNanos(long) line: 801
    java.lang.VirtualThread.sleepNanos(long) line: 983
    java.lang.Thread.sleepNanos(long) line: 507
    java.lang.Thread.sleep(Duration) line: 601
  ]
}

pinnedReason tells you why. The jdk.tracePinnedThreads system property that older articles recommend was removed in JDK 24; use the JFR event instead (see Profiling for more on JFR).

Some file system operations also block the carrier while they run. The scheduler compensates by temporarily adding a carrier thread, so these don't stall other virtual threads, but they don't scale like network I/O does.

ThreadLocal and virtual threads

ThreadLocal works in virtual threads, but each virtual thread gets its own copy of every thread-local it touches. A common trick is to cache an expensive or non-thread-safe object per thread, which only pays off when a few pooled threads are reused many times. With a thread per task, nothing is reused:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadLocalCost {
    static final AtomicInteger created = new AtomicInteger();

    // classic trick: one SimpleDateFormat per thread, because it isn't thread-safe
    static final ThreadLocal<SimpleDateFormat> FORMAT = ThreadLocal.withInitial(() -> {
        created.incrementAndGet();
        return new SimpleDateFormat("yyyy-MM-dd");
    });

    public static void main(String[] args) {
        run("fixed pool of 8", Executors.newFixedThreadPool(8));
        run("virtual thread per task", Executors.newVirtualThreadPerTaskExecutor());
    }

    static void run(String label, ExecutorService executor) {
        created.set(0);
        try (executor) {
            for (int i = 0; i < 10_000; i++) {
                executor.submit(() -> FORMAT.get().format(new Date(0)));
            }
        }
        System.out.printf("%-24s 10000 tasks, %5d SimpleDateFormat objects%n", label, created.get());
    }
}
fixed pool of 8          10000 tasks,     8 SimpleDateFormat objects
virtual thread per task  10000 tasks, 10000 SimpleDateFormat objects

The cache became pure overhead. Use a thread-safe, immutable alternative instead (here java.time.format.DateTimeFormatter, held in a static final field), or a shared pool of expensive objects. With a million threads, large per-thread values also add up to real memory.

ThreadLocal is still fine for what it is designed for: passing per-request context, such as a user or a transaction, down the call stack. For that, Java 25 adds ScopedValue (final, JEP 506), which is immutable, is bound only for the duration of a call and is cheaper with many threads. See Using ThreadLocal for the basics of ThreadLocal.

Thread dumps

The traditional jcmd <pid> Thread.print (and jstack) only lists platform threads, which is useless when the interesting work is in 10,000 virtual threads. Thread.dump_to_file includes virtual threads and can write JSON:

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DumpMe {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch release = new CountDownLatch(1);
        System.out.println("pid " + ProcessHandle.current().pid());
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 10_000; i++) {
                executor.submit(() -> {
                    release.await();   // all 10,000 threads wait here
                    return null;
                });
            }
            Thread.sleep(20_000);      // time to run jcmd
            release.countDown();
        }
    }
}

While it runs, from another terminal:

$ jcmd 4876 Thread.dump_to_file -format=json threads.json
4876:
Created C:\work\threads.json

The 13 MB file groups threads by thread container: the root container for platform threads, then one container for the executor with all 10,000 of its virtual threads, and one for the carrier pool. A virtual thread looks like this:

{
  "tid": "36",
  "time": "2026-10-17T22:21:40.391552300Z",
  "virtual": true,
  "name": "",
  "state": "WAITING",
  "parkBlocker": {
    "object": "java.util.concurrent.CountDownLatch$Sync@391f038b"
  },
  "stack": [
    "java.base\/java.lang.VirtualThread.park(VirtualThread.java:745)",
    "java.base\/java.lang.System$1.parkVirtualThread(System.java:2285)",
    "java.base\/java.util.concurrent.locks.LockSupport.park(LockSupport.java:221)",
    "java.base\/java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:790)",
    "java.base\/java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1139)",
    "java.base\/java.util.concurrent.CountDownLatch.await(CountDownLatch.java:230)",
    "DumpMe.lambda$main$0(DumpMe.java:12)",
    "java.base\/java.util.concurrent.FutureTask.run(FutureTask.java:328)",
    "java.base\/java.util.concurrent.ThreadPerTaskExecutor$ThreadBoundFuture.run(ThreadPerTaskExecutor.java:323)",
    "java.base\/java.lang.VirtualThread.run(VirtualThread.java:460)"
  ]
}

Being JSON, the dump is easy to query with jq or a short script, for example to count threads per state or find all threads parked on the same lock. Use -format=text (the default) for a plain-text dump. See Debugging for other jcmd commands.

Other things to know

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents