Revised 16 November 2026 for Java 25 and Quarkus 3.40.1.2. The original article URL is unchanged.
A Java service can spend much of a request waiting for another system. The code sends an HTTP request or executes a database query, then waits for the response before it can continue. Synchronous code expresses that sequence directly. The difficulty comes when enough requests arrive together that waiting consumes the available platform threads.
For this guide, I use a small REST application to separate two decisions that are easy to mix together: which thread handles a request, and whether that request starts concurrent subtasks. Virtual threads let us keep a synchronous call sequence while making many kinds of waiting less expensive. They don't automatically run consecutive calls in parallel, and they don't increase a database's connection limit.
We'll inspect the threads Quarkus selects, add a blocking delay, and run a bounded batch of independent tasks. The batch also has a deadline, so there is an explicit answer when those tasks take too long.
Start with the companion
Use JDK 25, with JAVA_HOME pointing to that installation. The example uses Quarkus 3.40.1.2. The Maven wrapper downloads Maven and dependencies on the first invocation; there is no database or broker to start.
Clone the companion repository and start the application:
git clone https://github.com/myfear/the-main-thread.git
cd the-main-thread/virtual-threads-demo
./mvnw quarkus:dev
If you already have the repository, update that checkout and enter the same directory. Quarkus listens on port 8080 by default. Keep this terminal open and use another terminal for the requests below.
The companion includes all source and tests. Its REST dependency is quarkus-rest-jackson, which gives us Quarkus REST and JSON responses. You don't need to add a separate virtual-threads extension to this REST application. The Maven compiler release is 25, matching the JDK used by the example.
For a fresh application, the equivalent starting point is the Quarkus CLI:
quarkus create app com.example:virtual-threads-demo \
--platform-bom=io.quarkus.platform:quarkus-bom:3.40.1.2 \
--extensions=rest-jackson --java=25 --no-code
The CLI command creates the project structure. Add the classes from the companion before trying its endpoints.
See where a request executes
Quarkus REST chooses an execution model from the method signature and annotations. A synchronous method returning an ordinary object normally runs on a worker thread. An asynchronous method returning Uni normally runs on an event-loop thread. @RunOnVirtualThread selects a virtual thread for a supported blocking endpoint. Other annotations can affect dispatch, so these rules describe the methods we're using here.
Open src/main/java/com/example/ThreadResource.java. These three methods return the current thread's name and whether it is virtual:
@GET
@Path("/event-loop")
@NonBlocking
public Uni<ThreadInfo> eventLoop() {
return Uni.createFrom().item(info());
}
@GET
@Path("/worker")
public ThreadInfo worker() {
return info();
}
@GET
@Path("/hello")
@RunOnVirtualThread
public ThreadInfo hello() {
return info();
}
The helper creates a ThreadInfo record from Thread.currentThread().getName() and Thread.currentThread().isVirtual(). There is no blocking operation in the event-loop method. Its result is available immediately, which makes it suitable for that execution model.
Call each endpoint:
curl --fail-with-body -sS http://localhost:8080/api/demo/event-loop
curl --fail-with-body -sS http://localhost:8080/api/demo/worker
curl --fail-with-body -sS http://localhost:8080/api/demo/hello
The event-loop and worker responses have virtual: false; their names identify different executors. The third response has virtual: true. Numeric suffixes in the names vary between runs, so use the boolean to check virtual-thread execution.
There is no global switch here that moves every method onto virtual threads. quarkus.virtual-threads.enabled defaults to true and can disable their use for annotated methods. It doesn't select every endpoint for virtual-thread dispatch. Changing quarkus.http.io-threads changes networking resources, not this method-level decision. The Quarkus configuration reference documents both settings.
Add a blocking delay
The /query method gives us a deliberately limited example of waiting:
@GET
@Path("/query")
@RunOnVirtualThread
public ThreadInfo query() throws InterruptedException {
Thread.sleep(500);
return info();
}
Call it with:
curl --fail-with-body -sS http://localhost:8080/api/demo/query
You get a response after roughly half a second, and virtual is true. During Thread.sleep, the virtual thread can unmount from its carrier, the platform thread that executes it. That carrier can then execute another virtual thread. Once the delay expires, the JVM schedules this virtual thread again so it can return the response.
Sleeping is a convenient way to see scheduling behavior. A real database introduces additional constraints: a connection pool, query execution time, locks, and the database server's capacity. Replacing a sleeping method with JDBC does not remove those constraints. Likewise, not every operation called “I/O” releases a carrier in the same way. Library implementations, filesystem calls, and native code require their own checks.
A method that calls two blocking services consecutively also waits for them consecutively. Choosing a virtual thread changes the cost of waiting; starting independent operations together requires another step.
Run independent subtasks together
The /parallel/{count} endpoint delegates to BatchService. Each child task sleeps and returns whether it ran on a virtual thread. The public entry point validates the input before creating tasks:
public Batch run(int count, int delayMs, int timeoutMs) {
if (count < 1 || count > 32 || delayMs < 0 || delayMs > 2000 || timeoutMs < 1 || timeoutMs > 5000) {
throw new BadRequestException("count: 1..32, delayMs: 0..2000, timeoutMs: 1..5000");
}
List<Callable<Boolean>> tasks = new ArrayList<>();
for (int i = 0; i < count; i++) {
tasks.add(() -> {
Thread.sleep(delayMs);
return Thread.currentThread().isVirtual();
});
}
return execute(tasks, timeoutMs);
}
The count is capped at 32. The service also admits at most four batches at a time, using one semaphore shared by the application instance. Together, these limits allow at most 128 child tasks across admitted batches. Request threads are separate from that count, and the limiter applies only to this batch endpoint.
Here is the execution method from the same class:
Batch execute(List<Callable<Boolean>> tasks, int timeoutMs) {
if (!batches.tryAcquire()) {
throw new ServiceUnavailableException("Four batches are already running", 1L);
}
long start = System.nanoTime();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
var futures = executor.invokeAll(tasks, timeoutMs, TimeUnit.MILLISECONDS);
boolean allVirtual = true;
for (var future : futures) {
if (future.isCancelled()) {
throw new WebApplicationException("Batch deadline exceeded", 504);
}
allVirtual &= future.get();
}
return new Batch(tasks.size(), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start), allVirtual);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ServiceUnavailableException("Request interrupted");
} catch (ExecutionException e) {
throw new InternalServerErrorException("Subtask failed", e.getCause());
} finally {
batches.release();
}
}
newVirtualThreadPerTaskExecutor() creates a virtual thread for each submitted task. invokeAll waits for the batch to finish or for the specified timeout. When the timeout expires, it cancels unfinished tasks. Our sleeping tasks respond to interruption, so they can terminate and release the batch's capacity.
The try-with-resources block closes the executor and waits for its threads to terminate. That gives the child tasks a clear lifetime, but it also means the timeout is not a hard return-time guarantee for arbitrary code. A task that ignores interruption can delay executor closure. HTTP clients and database operations need their own timeouts too.
The service preserves the request thread's interrupt status when its wait is interrupted. A failed child becomes an HTTP 500 response. Because this example uses invokeAll, a child failure is reported after batch collection; it does not immediately cancel every sibling. For the independent sleeping tasks that keeps the example small and its behavior explicit.
Try ten tasks with a half-second delay each:
curl --fail-with-body -sS \
'http://localhost:8080/api/demo/parallel/10?delayMs=500&timeoutMs=2000'
The response contains completed: 10, allVirtual: true, and an elapsedMs value. The sleeps overlap, so the batch can finish near one delay interval plus scheduling overhead. The exact duration depends on your machine and its current load.
This request measures a batch of tasks inside one HTTP request. Dividing the number of child tasks by the elapsed time does not tell us how many HTTP requests the service can sustain. To measure that, use an external load generator and report completed requests, latency, errors, CPU, and memory with the same resource limits across comparisons.
Exercise the failure paths
The accepted ranges are 1–32 tasks, 0–2000 milliseconds of delay, and a 1–5000 millisecond batch timeout. Defaults are 500 milliseconds of delay and a 2000 millisecond timeout.
These requests show input rejection and deadline expiry:
curl -i http://localhost:8080/api/demo/parallel/33
curl -i 'http://localhost:8080/api/demo/parallel/2?delayMs=1000&timeoutMs=10'
The first returns 400. The second returns 504 after cancelling unfinished tasks. When four batches are already admitted, an additional batch receives 503 with Retry-After: 1. The service rejects that request immediately rather than accumulating a queue of batches waiting for capacity.
Keep the children in this example independent of request-scoped beans and transactions. A raw Java executor does not automatically establish Quarkus request or transaction context in its child threads. If you introduce database access or request context into a task, define its lifecycle and propagation deliberately. Sharing one persistence context between concurrent tasks is a separate design problem.
Messaging, pinning, and diagnostics
Quarkus also supports @RunOnVirtualThread on Reactive Messaging consumers. The messaging integration manages dispatch and defaults to a maximum concurrency of 1024 for annotated methods. That is a messaging setting, not a global cap on REST requests. Select a limit that matches the consumer's downstream capacity, and check ordering and acknowledgement behavior before increasing parallelism. The messaging guide provides the Kafka setup; this companion does not start or test a broker.
Pinning advice needs a Java version attached to it. On Java 21–23, blocking while holding a synchronized monitor can pin a virtual thread to its carrier. Java 24 changed monitor handling through JEP 491, removing that common source of pinning. CPU-intensive computation can occupy a carrier regardless of that improvement, and native-code interactions need separate attention.
For Java 25, use JFR events and the Quarkus virtual-thread testing support. The old jdk.tracePinnedThreads switch is for Java 21–23. A pinning test can detect the behavior exercised by that test; it cannot tell you that your service has enough memory or downstream capacity under sustained load.
If you collect Micrometer metrics, virtual-thread metrics require the micrometer-java21 binder dependency alongside your metrics integration. The reference guide explains the dependency and configuration. Thread names and Thread.activeCount() are not a substitute for those diagnostics; activeCount() estimates platform threads in the current thread group.
Check the packaged application
Stop dev mode before running the complete verification command:
./mvnw verify -DskipITs=false
The tests check dispatch, input limits, completion, deadline cancellation, failure propagation, preservation of interrupt status, and rejection of a fifth concurrent batch. The HTTP suite also runs against the packaged JVM application. It deliberately avoids asserting a throughput number from a short sleep test.
Start the packaged application with:
java -jar target/quarkus-app/quarkus-run.jar
Keep the entire target/quarkus-app directory if you copy the application elsewhere. This edition validates JVM execution; the presence of virtual-thread support alone is not a native-image compatibility test.
Where Quarkus 4 fits
Quarkus 4 raises the minimum Java version to 21 and simplifies the framework's virtual-thread integration. This edition uses Quarkus 3.40.1.2 and Java 25; it does not claim a tested Quarkus 4 migration. The Java baseline explanation describes the framework change. Java's monitor-pinning improvement arrived in Java 24 independently of that framework upgrade.
The image-processing companion takes the next step into a request that also performs CPU-intensive computation. For an I/O-heavy service, begin by checking where requests execute and what they wait for. Then put limits around the resources those requests consume. That lets you keep the synchronous call sequence while making the service's concurrency and failure behavior explicit.



