Sub topic 7
Blocking Is Cheap Again: Sleep, I/O, and Locks
Blocking means a thread stops and waits for something before it can go on. It might wait for a timer, for data from the network, or for a lock that another thread holds. With platform threads, blocking is costly. The thread sits idle and still holds its operating system thread and its memory. Virtual threads change this. When a virtual thread blocks, it usually lets go of the real thread underneath it, so waiting costs almost nothing.
This chapter shows what happens when a virtual thread sleeps, does network I/O, or waits on a lock. You will run three small programs that show cheap blocking in action.
What "Blocking" Means
A blocking call is a method that does not return until something happens. Here are common examples:
Thread.sleep(...)waits for a set amount of time.socket.getInputStream().read()waits until bytes arrive from the network.lock.lock()waits until no other thread holds the lock.queue.take()waits until an item is in the queue.
In the last chapter you learned that a virtual thread runs on top of a carrier thread. A carrier thread is a platform thread that the JVM uses to run virtual threads. Mounting means putting a virtual thread on a carrier so it can run. Unmounting means taking it off.
The key idea of this chapter is simple. When a virtual thread makes most blocking calls, the JVM unmounts it. The carrier is then free to run a different virtual thread. When the wait ends, the JVM mounts the virtual thread again, often on a different carrier, and it carries on where it stopped.
Sleep: The Simplest Case
The program below runs 1,000 tasks. Each task sleeps for one second. It runs them twice: first on a fixed pool of 100 platform threads, then with one virtual thread per task.
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SleepCompare {
static void run(String label, ExecutorService executor) {
long start = System.nanoTime();
try (executor) {
for (int i = 0; i < 1_000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return null;
});
}
} // close() waits for every task to finish
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(label + ": " + ms + " ms");
}
public static void main(String[] args) {
run("100 platform threads", Executors.newFixedThreadPool(100));
run("virtual threads", Executors.newVirtualThreadPerTaskExecutor());
}
}Typical output looks like this:
100 platform threads: 10045 ms
virtual threads: 1032 msThe pool has only 100 threads, so only 100 tasks can sleep at the same time. The 1,000 tasks run in 10 rounds, which takes about 10 seconds. With virtual threads, all 1,000 tasks sleep at once. A sleeping virtual thread holds no carrier, so a handful of carriers is enough. The whole job takes about one second.
Network I/O: Waiting for Bytes
Network code spends most of its time waiting. A server waits for a client to connect. Then it waits for the client to send a request. The client waits for the reply. In the JDK, the classes in java.net, such as Socket and ServerSocket, were rewritten so that these waits unmount the virtual thread. Your code still looks like plain blocking code.
The next program starts a small echo server on your own machine. An echo server sends back whatever it receives. The program then starts 100 clients. Every connection, on both sides, gets its own virtual thread.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
public class EchoDemo {
static final int CLIENTS = 100;
public static void main(String[] args) throws Exception {
try (ServerSocket server = new ServerSocket(0, CLIENTS)) {
int port = server.getLocalPort();
Thread acceptor = Thread.ofVirtual().start(() -> serve(server));
try (var clients = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < CLIENTS; i++) {
int id = i;
clients.submit(() -> talk(port, id));
}
}
acceptor.join();
}
System.out.println("All clients done");
}
static void serve(ServerSocket server) {
try (var handlers = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < CLIENTS; i++) {
Socket socket = server.accept(); // waits for a client
handlers.submit(() -> echo(socket));
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
static Void echo(Socket socket) throws IOException {
try (socket;
var in = new BufferedReader(new InputStreamReader(
socket.getInputStream(), StandardCharsets.UTF_8));
var out = new PrintWriter(new OutputStreamWriter(
socket.getOutputStream(), StandardCharsets.UTF_8), true)) {
String line = in.readLine(); // waits for the client's message
out.println("echo: " + line);
}
return null;
}
static String talk(int port, int id) throws IOException {
try (var socket = new Socket(InetAddress.getLoopbackAddress(), port);
var in = new BufferedReader(new InputStreamReader(
socket.getInputStream(), StandardCharsets.UTF_8));
var out = new PrintWriter(new OutputStreamWriter(
socket.getOutputStream(), StandardCharsets.UTF_8), true)) {
out.println("hello " + id);
String reply = in.readLine(); // waits for the server's reply
if (id % 25 == 0) {
System.out.println(reply);
}
return reply;
}
}
}You should see a few lines such as echo: hello 0 and echo: hello 25, followed by All clients done. The line order may change from run to run.
Look at the style of the code. Every call is a plain blocking call: accept(), readLine(), println(). There are no callbacks or futures to chain together. This is the main promise of virtual threads. You write simple step-by-step code, and it still scales, because each wait gives the carrier back.
Locks and Queues: Waiting for Other Threads
Threads often wait for each other. The tools in java.util.concurrent, such as ReentrantLock, Semaphore, CountDownLatch, and BlockingQueue, all unmount a virtual thread that has to wait.
Here, 10,000 consumer tasks each wait to take one item from a queue. A consumer is a task that takes work out of a queue. The main thread then puts in 10,000 items.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class QueueWaiters {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(100);
AtomicInteger handled = new AtomicInteger();
int consumers = 10_000;
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < consumers; i++) {
executor.submit(() -> {
int item = queue.take(); // waits without holding a carrier
handled.incrementAndGet();
return item;
});
}
for (int i = 0; i < consumers; i++) {
queue.put(i);
}
}
System.out.println("Handled " + handled.get() + " items");
}
}The output is Handled 10000 items. For a while, thousands of virtual threads sit waiting in take(). With platform threads, that would mean 10,000 operating system threads. With virtual threads, it means 10,000 small objects on the heap.
Which Blocking Calls Unmount?
Most blocking calls in the JDK unmount, but a few do not. The table gives a beginner-friendly summary.
| Operation | What happens to the carrier |
|---|---|
| `Thread.sleep` | Released while sleeping |
| Socket I/O (`Socket`, `ServerSocket`, `HttpClient`) | Released while waiting for data |
| `ReentrantLock`, `Semaphore`, `BlockingQueue`, `CountDownLatch` | Released while waiting |
| `Future.get()`, `Thread.join()` | Released while waiting |
| File I/O (`FileInputStream`, `Files.readAllBytes`) | Usually held; the JVM may add a temporary extra carrier |
| `synchronized` block that blocks inside, or `Object.wait()` | Held on JDK 21 to 23; released on JDK 24 and later |
| Native code (JNI) that blocks | Held |
Why This Changes How You Write Code
With platform threads, blocking was expensive, so developers worked around it. They used small thread pools, asynchronous APIs, and callback chains to avoid holding a thread while waiting. That code is hard to read and hard to debug.
With virtual threads, the cost of waiting moves from "one operating system thread" to "a few hundred bytes of heap memory." This means you can:
- Write one task as a simple sequence of steps, even if many steps wait.
- Give each request or connection its own thread.
- Use normal
try/catchand normal stack traces when things go wrong.
Blocking is cheap, but the work you wait on is not. A database can still handle only so many connections at once. The chapter on semaphores shows how to protect such resources.
Exercise
In SleepCompare, what total time would you expect if you changed the fixed pool to 500 platform threads but kept 1,000 tasks that each sleep for one second? Why does the virtual thread version not depend on a number like this?
Show answer
About 2 seconds, because 500 threads run the 1,000 tasks in two rounds. The virtual thread version gives every task its own thread, and a sleeping virtual thread gives back its carrier, so all 1,000 tasks can sleep at once and the job takes about 1 second.
Exercise
A virtual thread calls queue.take() on an empty BlockingQueue. Describe what happens to the virtual thread and to its carrier thread until an item arrives.
Show answer
The JVM unmounts the virtual thread and saves its state on the heap. The carrier thread is free to run other virtual threads. When another thread puts an item in the queue, the scheduler mounts the waiting virtual thread on an available carrier, which may be a different one, and take() returns the item.
Exercise
You are on JDK 21. A method holds a synchronized lock while it waits 200 ms for a network reply. Thousands of virtual threads call it. What problem may you see, and what is a simple fix?
Show answer
Each waiting virtual thread is pinned and keeps its carrier, so the few carriers fill up and throughput drops. Replace the synchronized block with a ReentrantLock (lock() in a try, unlock() in finally) so the virtual thread can unmount while it waits, or upgrade to JDK 24 or later.