Video in progress

Strong Middle 📁 IO and NIO

How did Java 21 virtual threads change the way we look at blocking IO? Do we still need NIO and the reactive approach?

When a virtual thread waits in blocking IO it frees the carrier thread, so plain InputStream/JDBC code can hold tens of thousands of simultaneous connections. But blocking inside synchronized (before Java 24) and file IO can still tie up a carrier, and reactive still makes sense for backpressure and streaming.

📖 Answer

The choice used to be hard: simple, easy-to-read blocking code but a platform thread per connection; or NIO/reactive, which scales but is hard to read and debug.

With virtual threads, the JDK performs socket operations internally as non-blocking: the thread "sleeps" while the carrier picks up other work. And you write plain code:

try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
    for (Socket s : acceptLoop()) {
        exec.submit(() -> handle(s)); // blocking read/write is not a problem
    }
}

In Spring Boot 3.2+, spring.threads.virtual.enabled=true runs Tomcat requests on virtual threads.

Things still worth watching:

  • pinning: on Java 21-23, if a virtual thread waits for IO inside a synchronized block, it blocks the carrier. You find it with -Djdk.tracePinnedThreads=full or the JFR jdk.VirtualThreadPinned event. Java 24 (JEP 491) mostly removed this limitation;
  • file IO on many OSes is not truly non-blocking: the JDK temporarily expands the carrier pool;
  • resources stay limited: a pool with 50 DB connections still queues 10,000 virtual threads;
  • keeping a big object in a ThreadLocal eats memory with millions of threads.

When reactive (WebFlux) still makes sense: endless streams, flows that need backpressure, a stack that is already reactive. For a plain CRUD service, virtual threads are often the simpler path.