Video in progress

How does blocking file IO work with virtual threads? Is it different from socket IO?

It is different. With socket IO the virtual thread detaches from the carrier and the wait happens in the kernel through epoll. OSes usually don't make file IO non-blocking, so the virtual thread ties up the carrier; the JDK compensates by temporarily growing the carrier pool.

📖 Answer

In Java 21, Socket, SocketChannel and the libraries built on them (JDBC drivers, HTTP clients) have been rewritten for virtual threads: if a read would block, the virtual thread is "parked" and the carrier takes other work. If a thousand virtual threads wait on a thousand sockets, the number of carriers doesn't change.

The file system is different. On Linux, a read on a regular file is always considered "ready", the real wait happens inside the disk, and you can't watch it with epoll. So FileInputStream.read on a virtual thread really does block the carrier. The JDK knows about this: for such calls it temporarily adds an extra carrier through the ForkJoinPool managed blocking mechanism (the upper bound is jdk.virtualThreadScheduler.maxPoolSize, default 256).

What this means in practice:

  • If thousands of virtual threads read from a slow disk at the same time, the number of carriers hits the limit and other virtual threads queue up too.
  • Doing IO inside a synchronized block caused "pinning" in Java 21-23: the virtual thread couldn't detach from the carrier. Java 24 (JEP 491) removed that limitation, but it is still relevant on the 21 LTS; you find it with -Djdk.tracePinnedThreads=full.
  • Disk throughput doesn't grow with the number of threads. 10 thousand parallel file reads don't run 10 thousand times faster: the disk has its own queue.

This is what I usually do: I freely give network IO to virtual threads, and I route heavy file IO through a separate bounded pool or a Semaphore, so that even if the disk gets jammed, the whole service doesn't freeze.