Java tutorial · Intermediate · 12 min

Virtual threads: more throughput for a banking API without a rewrite

A customer-view API that queries KYC, the scoring engine and core banking spends most of its time waiting. With the virtual threads of Java 21 and later, you keep simple, readable blocking code while serving far more concurrent requests.

Tested source code, free to use: GitHub, Scopas-Team/java-finance-tutorials (Apache 2.0 licence)

The problem: threads that wait

In a classic server, each request holds a platform thread (an operating-system thread) for its whole duration, including while it waits for a network response. The pool has a few hundred threads: beyond that, requests queue even if the CPU is almost idle. Reactive programming solves this, but at the cost of code that is harder to write, read and debug.

A virtual thread is a lightweight thread managed by the JVM: when it blocks on I/O, it releases the OS thread that was carrying it. You can create millions of them.

1. Running three calls in parallel

public CustomerView customerView(String customerId) throws Exception {
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        Future<KycRecord> kyc = executor.submit(() -> kycService.record(customerId));
        Future<Score> score = executor.submit(() -> scoringService.score(customerId));
        Future<List<Account>> accounts = executor.submit(() -> coreBanking.accounts(customerId));
        return new CustomerView(kyc.get(), score.get(), accounts.get());
    }
}

Each task runs in its own virtual thread; the try waits for all of them when the executor closes. The request now takes as long as the slowest call rather than the sum of all three. The client code (kycService and so on) stays blocking and unchanged.

2. Turning virtual threads on in the framework

Spring Boot 3.2 and later: application.properties

spring.threads.virtual.enabled=true

Tomcat, @Async tasks and message listeners then use virtual threads.

Quarkus: per endpoint

@Path("/customers")
public class CustomerResource {
    @GET
    @Path("/{id}")
    @RunOnVirtualThread
    public CustomerView view(@PathParam("id") String id) {
        return service.customerView(id);
    }
}

3. Protecting what does not scale

This is pitfall number one. Virtual threads lift the server's limit, and the pressure moves to the systems you call: the database, the scoring engine, a package that accepts twenty connections. The connection pool (HikariCP) remains the limit for the database. For a remote service, set an explicit limit:

private final Semaphore scoringLimit = new Semaphore(20);

Score score(String customerId) throws InterruptedException {
    scoringLimit.acquire();
    try {
        return scoringService.score(customerId);
    } finally {
        scoringLimit.release();
    }
}

Never pool virtual threads to limit load: they are meant to be created on demand. Limit the resource, not the threads.

4. A multi-threaded event consumer

The same idea works for an event stream, for example payments published to Kafka. Each event calls slow services (fraud check, sanctions screening, booking): processing them one at a time caps throughput at the inverse of the latency. Three constraints shape the design:

try (KafkaConsumer<String, Payment> consumer = new KafkaConsumer<>(config)) {
    consumer.subscribe(List.of("payments"));
    while (running) {
        ConsumerRecords<String, Payment> records = consumer.poll(Duration.ofMillis(500));
        if (records.isEmpty()) continue;

        // 1. Group by key (the account number), keeping the read order
        Map<String, List<Payment>> byAccount = new LinkedHashMap<>();
        for (ConsumerRecord<String, Payment> r : records) {
            byAccount.computeIfAbsent(r.key(), k -> new ArrayList<>()).add(r.value());
        }

        // 2. One virtual thread per account: accounts in parallel, one account's events in order
        List<Future<Void>> tasks = new ArrayList<>();
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (List<Payment> payments : byAccount.values()) {
                tasks.add(executor.submit(() -> {
                    for (Payment p : payments) process(p);
                    return null;
                }));
            }
        } // waits for every task to finish

        // 3. A failure surfaces here, before the commit: the events will be read again
        for (Future<Void> t : tasks) t.get();
        consumer.commitSync();
    }
}

What this pattern assumes, and what you need to check:

The same pattern works for a JMS queue or an in-process queue. With Spring for Apache Kafka, spring.threads.virtual.enabled=true also runs the listener containers on virtual threads, but parallelism is still bounded by the number of partitions: to parallelise by key within a partition, you need a pattern like this one or a dedicated library such as Confluent Parallel Consumer.

5. Avoiding pinning

A virtual thread stays "pinned" to its OS thread when it blocks during a native call and, up to Java 23, inside a synchronized block. Java 24 lifted that second limit (JEP 491): one more reason to target a recent version. To find the remaining cases, record the JFR event jdk.VirtualThreadPinned:

java -XX:StartFlightRecording=filename=pin.jfr,settings=profile -jar app.jar
jfr print --events jdk.VirtualThreadPinned pin.jfr

6. ThreadLocal and ScopedValue

A ThreadLocal caching a heavy object (a formatter, a buffer) used to be amortised over a few hundred threads; with one thread per request it is recreated every time and memory climbs. To pass context (user, correlation ID), Java 25 offers ScopedValue (JEP 506), immutable and bound to a scope:

static final ScopedValue<String> CORRELATION_ID = ScopedValue.newInstance();

ScopedValue.where(CORRELATION_ID, request.correlationId())
           .run(() -> handle(request));

// further down the call stack
log.info("processing {}", CORRELATION_ID.get());

7. Measure before and after

The gains depend on how much of each request is spent waiting. Replay the same load test (Gatling, k6 or JMeter) before and after, with the same data volume, and compare: maximum throughput, 95th and 99th percentile latency, and the load on the systems you call. On a compute-bound service (valuation, risk simulation), virtual threads bring nothing: the CPU is already busy.

Key points

An API hitting its limits?

We diagnose your Java applications, from the JDK version to the bottlenecks, and help you modernise them without a full rewrite.

The diagnostic All tutorials

Worth a look