Java and Spring Level 3 This level · 26 of 56
Medium java spring

How do you build a highly concurrent app without running out of platform threads?

The 30 second answer

For blocking network and disk work I use virtual threads, which are final in Java 21. They are cheap, so one per request or task is fine, and when they block on that work they release the carrier thread. I don't pool them. Instead, I limit scarce resources like database connections with the connection pool or a semaphore, not with the thread count.

Could you say this in an interview?

For blocking I/O work, use virtual threads (JEP 444, final in Java 21): Executors.newVirtualThreadPerTaskExecutor(). They are cheap, so one per request is fine, and when they block on I/O they unmount from the carrier thread. Don't pool them. Limit access to scarce resources such as DB connections with a semaphore or the pool itself, not by the thread count. Follow-up: What is pinning? (In Java 21, a virtual thread inside a synchronized block or native call can't unmount while blocked, per JEP 444; prefer ReentrantLock around long blocking calls.)

One virtual thread per request, with a semaphore guarding the database:

static final Semaphore dbPermits = new Semaphore(10);   // match the DB pool size

static void handle(Request request) {
    dbPermits.acquireUninterruptibly();                 // a waiting virtual thread unmounts here
    try {
        queryDatabase(request);
    } finally {
        dbPermits.release();
    }
}

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (Request request : requests) {
        executor.submit(() -> handle(request));          // one virtual thread per request
    }
}

Alternate interview scenarios

"Do virtual threads help with CPU-bound work, and what is pinning?"

They do not help CPU-bound work. JEP 444 says that having many more threads than processor cores cannot improve throughput when the workload is CPU-bound, and the Thread Javadoc says virtual threads "are not intended for long running CPU intensive operations." For that work I keep a small pool of platform threads, about the core count. Pinning is a separate I/O-scalability issue. In Java 21, 22 and 23, a virtual thread that blocks inside a synchronized method or block, or in a native call, stays pinned to its carrier, so that platform thread cannot run other virtual threads. JEP 444 suggested ReentrantLock around frequent, long blocking operations, and -Djdk.tracePinnedThreads to find them. Java 24 (JEP 491) removed the synchronized pinning case; native calls can still pin.

Sources (4)
  1. JEP 444: Virtual Threadsopenjdk.org
  2. Thread Javadoc (Java 21): virtual threadsdocs.oracle.com
  3. JEP 491: Synchronize Virtual Threads without Pinningopenjdk.org
  4. Semaphore Javadoc (Java 21)docs.oracle.com
Previous
Next