Programming languages · Advanced · 22 min
Handle thousands of blocking calls with Java virtual threads
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Java 25 LTS (Eclipse Temurin 25.0.5)
You will make 10,000 calls to a slow local HTTP endpoint with plain blocking Java code, measure them on 200 platform threads and then on virtual threads, and learn where virtual threads help, where they do not, and how to pass request data with ScopedValue.
On this page
Most backend code spends its time waiting: for a database, another service or a slow client. In classic Java each waiting request holds a platform thread, which is a wrapper around an operating system thread with a large stack reserved up front. Servers cap those threads at a few hundred, so the cap, not the CPU, decides how many requests you can have in flight.
Virtual threads, final since Java 21, remove that cap. A virtual thread is a Java object managed by the JVM. When it blocks on I/O or sleep, the JVM takes it off the operating system thread it was running on, called its carrier, and runs another virtual thread there. You keep writing ordinary blocking code, and you can have tens of thousands of threads.
In this tutorial you build a local endpoint that takes one second to answer, call it 10,000 times, and time the same client code on a fixed pool of 200 platform threads and on virtual threads. Then you look at the carriers, show that CPU-bound work gains nothing, check for pinning, and pass a request ID with ScopedValue. Every program is a single .java file that the java launcher compiles and runs, so there is no build tool to set up. The timings you see are your own: they depend on your machine.
Step 1 · Check Java and create a folder
Virtual threads exist from Java 21, but use Java 25 LTS: from Java 24, code inside synchronized blocks no longer holds on to its carrier, which removes the most common problem with them. Check your version and make a folder for the demo:
java -version
mkdir -p ~/vthreads-demo
cd ~/vthreads-demoCheck it worked
The first line of the output starts with openjdk version "25 (followed by the patch number, such as 25.0.5). If it shows 21 or older, install Java 25 first, as in Hello World in Java.
Step 2 · Write a slow endpoint
The JDK ships a small HTTP server in the jdk.httpserver module. Create SlowServer.java with one route, /slow, that waits one second and then answers ok. That one second stands in for a slow database query or a partner API:
cat > SlowServer.java <<'JAVA'
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
public class SlowServer {
public static void main(String[] args) throws Exception {
// 10,000 is the queue of connections waiting to be accepted.
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 8080), 10_000);
server.createContext("/slow", exchange -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
byte[] body = "ok\n".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, body.length);
try (var out = exchange.getResponseBody()) {
out.write(body);
}
});
// Each request gets its own virtual thread, so the server never runs out of threads.
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.start();
System.out.println("Listening on http://127.0.0.1:8080/slow");
}
}
JAVAThe server itself already uses virtual threads, through setExecutor. That is deliberate: the experiment is about the client, and a server limited to a few hundred threads would hide the difference. You will see the same one-line change on the client side next.
In your second terminal, go to the same folder and start the server. Leave it running:
cd ~/vthreads-demo
java SlowServer.javaCheck it worked
The second terminal prints Listening on http://127.0.0.1:8080/slow after a second or two, while java compiles the file in memory. Back in the first terminal, call the route once:
curl -s -w '%{time_total}\n' http://127.0.0.1:8080/slowIt prints ok, then a time a little over one second, such as 1.004512.
Step 3 · Make 10,000 calls on 200 platform threads
Create Client.java. It uses the JDK's HttpClient and its blocking send method: each call waits for the answer before it returns, exactly like a JDBC query or a call through a typical SDK. The first argument picks the executor: a fixed pool of 200 platform threads, or a new virtual thread per task. The task code is the same in both cases:
cat > Client.java <<'JAVA'
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class Client {
static final HttpClient HTTP = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(30))
.build();
static final URI SLOW = URI.create("http://127.0.0.1:8080/slow");
// Plain blocking code: send() waits until the answer arrives.
static void callOnce() throws Exception {
HttpRequest request = HttpRequest.newBuilder(SLOW).timeout(Duration.ofSeconds(60)).build();
HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IllegalStateException("status " + response.statusCode());
}
}
public static void main(String[] args) throws Exception {
String mode = args[0];
int calls = Integer.parseInt(args[1]);
AtomicInteger ok = new AtomicInteger();
AtomicReference<String> firstError = new AtomicReference<>();
long start = System.nanoTime();
try (ExecutorService pool = mode.equals("virtual")
? Executors.newVirtualThreadPerTaskExecutor()
: Executors.newFixedThreadPool(200)) {
for (int i = 0; i < calls; i++) {
pool.submit(() -> {
try {
callOnce();
ok.incrementAndGet();
} catch (Exception e) {
firstError.compareAndSet(null, e.toString());
}
});
}
} // close() waits for every task to finish
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.printf("%s: %d of %d calls ok in %d ms%n", mode, ok.get(), calls, ms);
if (firstError.get() != null) {
System.out.println("first error: " + firstError.get());
}
}
}
JAVAExecutorService is AutoCloseable since Java 19, and close() waits for all submitted tasks, so the timer stops when the last call has finished. Run the platform version. With 200 threads and a one-second wait, 10,000 calls need at least 50 rounds, so expect it to take close to a minute:
java Client.java platform 10000 | tee platform.txtCheck it worked
The output is one line such as platform: 10000 of 10000 calls ok in 51874 ms. The count must be 10000 of 10000, and the time a little over 50 seconds. Raising the pool to 10,000 platform threads would work on a big machine, but each one costs an operating system thread and its stack, which is why servers do not do it.
Step 4 · Run the same code on virtual threads
Now run the client with virtual. The only difference in the code is Executors.newVirtualThreadPerTaskExecutor() in place of the fixed pool. Every call gets its own thread, so all 10,000 can wait at the same time:
java Client.java virtual 10000 | tee virtual.txtCheck it worked
The output is something like virtual: 10000 of 10000 calls ok in 2390 ms: a few seconds, against close to a minute before. The time is above one second because 10,000 connections still have to be opened. If you see first error: ... Too many open files, your shell limits open files; run ulimit -n 65536 in both terminals, restart the server and try again.
This is the case virtual threads are made for: many tasks, each mostly waiting. It matters on modest hardware too. An API serving mobile users on slow or prepaid connections, common across much of Africa, holds each request open for longer, and a server on a small virtual machine can keep thousands of those waiting without a bigger thread pool.
Step 5 · See the carrier threads underneath
Virtual threads still run on operating system threads, just far fewer of them. The JVM keeps a small pool of carriers, by default one per CPU core, and mounts whichever virtual thread is ready to run. A virtual thread's toString() names the carrier it is mounted on after the @. Create Carriers.java, which starts 10,000 virtual threads that each sleep for a second and records which carriers they ran on:
cat > Carriers.java <<'JAVA'
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
public class Carriers {
public static void main(String[] args) {
Set<String> carriers = ConcurrentHashMap.newKeySet();
int threads = 10_000;
long start = System.nanoTime();
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < threads; i++) {
pool.submit(() -> {
Thread.sleep(1000);
carriers.add(carrierName());
return null;
});
}
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.printf("%d virtual threads slept 1 s each in %d ms%n", threads, ms);
System.out.printf("carrier threads used: %d (CPU cores: %d)%n",
carriers.size(), Runtime.getRuntime().availableProcessors());
System.out.println("one of them: " + carriers.iterator().next());
}
// Looks like VirtualThread[#25]/runnable@ForkJoinPool-1-worker-3
static String carrierName() {
String self = Thread.currentThread().toString();
int at = self.indexOf('@');
return at < 0 ? self : self.substring(at + 1);
}
}
JAVA
java Carriers.java | tee carriers.txtCheck it worked
The output looks something like this, with your own core count:
10000 virtual threads slept 1 s each in 1121 ms
carrier threads used: 4 (CPU cores: 4)
one of them: ForkJoinPool-1-worker-2Ten thousand threads shared a handful of carriers, about one per core. While a virtual thread sleeps or waits on a socket, it is not on any carrier at all: its stack is saved on the heap, which is why it costs kilobytes, not a whole operating system thread.
Step 6 · Show that CPU work does not get faster
A virtual thread does not add CPU. If a task is busy computing, it holds its carrier the whole time, and the work still runs on the same number of cores. Create CpuWork.java, which runs CPU-heavy tasks on a pool sized to your cores and then on virtual threads:
cat > CpuWork.java <<'JAVA'
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 CpuWork {
// Pure computation: no I/O, no waiting.
static long crunch(long seed) {
long x = seed;
for (int i = 0; i < 50_000_000; i++) {
x = x * 6364136223846793005L + 1442695040888963407L;
}
return x;
}
static void time(String label, ExecutorService pool, int tasks) throws Exception {
long start = System.nanoTime();
long checksum = 0;
try (pool) {
List<Future<Long>> results = new ArrayList<>();
for (int i = 0; i < tasks; i++) {
long seed = i;
results.add(pool.submit(() -> crunch(seed)));
}
for (Future<Long> f : results) {
checksum += f.get();
}
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.printf("%s: %d tasks in %d ms (checksum %d)%n", label, tasks, ms, checksum);
}
public static void main(String[] args) throws Exception {
int cores = Runtime.getRuntime().availableProcessors();
int tasks = cores * 8;
time("warm-up", Executors.newFixedThreadPool(cores), tasks);
time("platform", Executors.newFixedThreadPool(cores), tasks);
time("virtual", Executors.newVirtualThreadPerTaskExecutor(), tasks);
}
}
JAVA
java CpuWork.java | tee cpu.txtThe warm-up round lets the JIT compiler optimise crunch first, so the two measured rounds compare fairly.
Check it worked
You see three lines with the same checksum, and the platform and virtual times close to each other, for example platform: 32 tasks in 412 ms and virtual: 32 tasks in 398 ms. For work like this, keep a pool sized to your cores (or use parallel streams); virtual threads help only when tasks wait.
Step 7 · Check that synchronized code no longer pins
A virtual thread is pinned when it blocks but cannot leave its carrier, so the carrier sits idle. Up to Java 23 the usual cause was blocking inside a synchronized block or method, and many libraries are full of those. Java 24 changed the JVM so a virtual thread can unmount while it holds a monitor. Some cases can still pin on Java 25: blocking while inside native code (JNI or the Foreign Function API) and blocking during class initialisation. The JDK Flight Recorder reports each one as a jdk.VirtualThreadPinned event.
Create Pinning.java. It starts 2,000 virtual threads that each take their own lock with synchronized and sleep for 100 ms while holding it:
cat > Pinning.java <<'JAVA'
import java.util.concurrent.Executors;
public class Pinning {
public static void main(String[] args) {
int tasks = 2_000;
Object[] locks = new Object[tasks];
for (int i = 0; i < tasks; i++) {
locks[i] = new Object();
}
long start = System.nanoTime();
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < tasks; i++) {
Object lock = locks[i];
pool.submit(() -> {
synchronized (lock) {
Thread.sleep(100); // blocks while holding a monitor
}
return null;
});
}
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.printf("%d synchronized sleeps of 100 ms in %d ms%n", tasks, ms);
}
}
JAVA
java -XX:StartFlightRecording=filename=pinning.jfr,dumponexit=true Pinning.java | tee pinning.txt
jfr print --events jdk.VirtualThreadPinned pinning.jfr > pinned-events.txt
wc -l < pinned-events.txt-XX:StartFlightRecording records the run with the default settings, which log any pin that lasts longer than 20 ms. jfr is the recording reader that comes with the JDK.
Check it worked
The program prints a line such as 2000 synchronized sleeps of 100 ms in 287 ms, after a message from the flight recorder. The wc -l line prints 0: no pinned events. On Java 21 the same program pins every carrier, and with four cores it takes around 50 seconds. If you must stay on Java 21 for now, replace synchronized around blocking calls with java.util.concurrent.locks.ReentrantLock, which never pinned.
Step 8 · Pass request data with ScopedValue
Servers often keep per-request data, such as a request ID for logs, in a ThreadLocal. With a million short-lived virtual threads that gets expensive, and a ThreadLocal can be changed by any code at any time and leaks if nobody removes it. ScopedValue, final in Java 25, is the replacement: you bind a value for the length of one call, everything that call runs can read it, and it is gone when the call returns. Create RequestScope.java:
cat > RequestScope.java <<'JAVA'
import java.util.concurrent.Executors;
public class RequestScope {
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
// Deep in the call stack, with no request ID parameter.
static void log(String message) {
String id = REQUEST_ID.isBound() ? REQUEST_ID.get() : "no-request";
System.out.println("[" + id + "] " + message);
}
static void loadOrder() {
log("loading order");
}
static void handle() {
log("start");
loadOrder();
log("done");
}
public static void main(String[] args) {
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 1; i <= 3; i++) {
String id = "req-" + i;
pool.submit(() -> ScopedValue.where(REQUEST_ID, id).run(RequestScope::handle));
}
}
log("after all requests");
}
}
JAVA
java RequestScope.java | sort | tee scope.txtScopedValue.where(...).run(...) binds REQUEST_ID only while handle runs, on that virtual thread. The three requests run at the same time, so their lines interleave; sort groups them.
Check it worked
You see ten lines: [no-request] after all requests, then [req-1] done, [req-1] loading order, [req-1] start and the same three for req-2 and req-3. Each request saw only its own ID, and the code in main, outside any binding, saw none.
Step 9 · Turn them on in Spring Boot, then clean up
In a Spring Boot application you do not create executors yourself. Set one property in src/main/resources/application.properties and the embedded web server, @Async methods and scheduled tasks run on virtual threads:
spring.threads.virtual.enabled=true
spring.main.keep-alive=trueVirtual threads are daemon threads, so an application with nothing else holding the JVM open could exit; spring.main.keep-alive=true stops that. Thread pool size properties no longer have any effect once this is on. Measure your own endpoints before and after, and if throughput drops, record with the flight recorder as in the previous step to look for pinning. Build a REST API with Spring Boot 4 sets up an application to try this on.
To finish, stop the server with Ctrl+C in the second terminal, then remove the demo folder:
cd ~
rm -rf ~/vthreads-demoCheck it worked
ls ~/vthreads-demo reports that there is no such file or directory, and curl http://127.0.0.1:8080/slow fails with a connection error because the server has stopped.
Next steps
- Process the results of many calls in one pipeline: transform collections with Java streams.
- Put virtual threads behind a real web API: build a REST API with Spring Boot 4.
- Compare with another language's lightweight threads: run work concurrently in Go with goroutines and channels.
- See the same waiting-versus-computing split in Python: speed up Python with threads and processes.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials