Sub topic 7
Blocking Is Cheap Again: Sleep, I/O, and Locks
In older Java code, programmers worked hard to avoid blocking. Blocking means a thread stops and waits for something, such as a timer, a network reply, or a lock. A blocked platform thread does no work, but it still holds an operating system thread and its memory. With virtual threads, you can write the same simple waiting code, and the waiting costs very little.
What Happens When a Virtual Thread Waits
You met carrier threads in the previous chapter. A carrier thread is a platform thread that runs virtual threads. When a virtual thread calls a blocking method, the JDK does three things:
- It saves the virtual thread's stack to the heap. This step is called unmounting.
- It frees the carrier, so the carrier can run a different virtual thread.
- When the wait ends, the JDK puts the virtual thread back on a carrier, and the thread continues. This step is called mounting.
Your code doesn't change. It still reads like ordinary step-by-step Java.
Which Blocking Calls Unmount
Most of the blocking methods you use every day are already written to unmount.
| Operation | Example | Frees the carrier? |
|---|---|---|
| Sleeping | `Thread.sleep(...)` | Yes |
| Network I/O | socket reads, `HttpClient.send(...)` | Yes |
| Locks | `ReentrantLock.lock()` | Yes |
| Queues | `BlockingQueue.take()` | Yes |
| Waiting for results | `Future.get()`, `Thread.join()` | Yes |
| File I/O | `Files.readString(...)` | Not fully. The JDK briefly adds an extra carrier to make up for it. |
A Worked Example
This program starts 5,000 virtual threads. Each one sleeps for half a second, then waits for a shared lock and adds one to a counter. Both steps block.
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
public class BlockingDemo {
private static final ReentrantLock LOCK = new ReentrantLock();
private static int counter = 0;
public static void main(String[] args) {
Instant start = Instant.now();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 5_000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(500)); // blocks: unmounts
LOCK.lock(); // may block: unmounts
try {
counter++;
} finally {
LOCK.unlock();
}
return null;
});
}
} // waits for every task to finish
long ms = Duration.between(start, Instant.now()).toMillis();
System.out.println("counter = " + counter + " in " + ms + " ms");
}
}When you run it, you should see counter = 5000 after a little more than 500 milliseconds. All 5,000 threads sleep at the same time on only a few carriers. A pool of 10 platform threads would need about 250 seconds, because only 10 tasks could sleep at once.
The lambda ends with return null. That makes it a Callable, which is a task that can throw checked exceptions such as InterruptedException. As a result, you don't need a try/catch around sleep.
Key Points
- Blocking still pauses your task, but it no longer ties up an operating system thread.
- Sleep, network I/O,
java.util.concurrentlocks, and queues all unmount the virtual thread. - File I/O and
synchronized(before JDK 24) are the main exceptions.
Exercise
A virtual thread calls ReentrantLock.lock(), but another thread already holds the lock. What happens to the carrier thread while it waits?
Show answer
The virtual thread unmounts and its stack is saved to the heap. The carrier is free to run other virtual threads. When the lock becomes available, the virtual thread mounts on a carrier again and continues.
Exercise
In BlockingDemo, why does the whole program take only about half a second, even though there are 5,000 tasks that each sleep for 500 ms?
Show answer
Each sleeping virtual thread releases its carrier, so all 5,000 sleeps happen at the same time. The few carrier threads are only busy for the tiny amount of real work each task does.