Virtual threads and structured concurrency question 122 of 180 mid
Is Thread.sleep still a bad idea on a virtual thread?
- Yes, it blocks a carrier thread
- Correct: No:
sleepon a virtual thread unmounts it, costing no OS thread, which is one of the clearest illustrations of what changed - It throws
UnsupportedOperationException - It is converted into a busy wait
Thread.sleep is one of the JDK calls made virtual-thread aware. On a virtual thread it parks the
continuation and frees the carrier, so a million sleeping virtual threads consume essentially no OS
resources. That is the standard demonstration: start a million threads that each sleep a second, and
watch it finish in about a second.
The same retrofit covers java.net sockets, NIO channels, java.util.concurrent locks and queues,
and Process.waitFor. What is not covered: synchronized and Object.wait before JDK 24, native calls,
and file I/O on some platforms, where the JVM falls back to a platform thread underneath.
Sleeping as a way to coordinate threads remains a bad idea, but for reasons of correctness rather than cost.
Quiz yourself on Virtual threads and structured concurrency Suggest a correction