Virtual threads
A platform thread is an operating system thread, and a program can afford a few thousand of them at most. A virtual thread is a thread the JVM schedules onto a much smaller pool of platform threads; it costs a few hundred bytes and blocks without holding a carrier while it waits. JDK 21 has them, and the API is the same Thread as before.
A virtual thread and the one underneath
Thread.ofVirtual() is a builder with a name and a start method, and Thread.startVirtualThread is the shorthand for a thread that is started at once. Inside the task, Thread.currentThread().isVirtual says which kind it is:
virtual_threads.scala
@main def virtual_threads(): Unit =
println(s"main thread is virtual: ${Thread.currentThread().isVirtual}")
val builder = Thread.ofVirtual().name("worker-", 0)
val worker = builder.start(() => println(s"${Thread.currentThread().getName} is virtual"))
worker.join()
val started = Thread.startVirtualThread(() => println("started from a virtual thread"))
started.join()
scala-cli run --server=false virtual_threads.scala
main thread is virtual: false
worker-0 is virtual
started from a virtual thread
The main thread is a platform thread, which is why the first line says false: a program still starts on an ordinary thread. The name worker- with a counter is the one the builder gave the thread, and the task reads its own name from inside. A virtual thread runs on a carrier thread of a fork-join pool, and it leaves that carrier as soon as it blocks on I/O or on a lock, which is the saving.
A million tasks at once
The point of the cheap thread is the number. A program that starts a million virtual threads, each adding one number to a shared total, finishes in a few seconds, and the counters confirm that every thread really was virtual:
million.scala
import java.util.concurrent.atomic.{AtomicInteger, AtomicLong}
@main def million(): Unit =
val sum = AtomicLong(0)
val virtual = AtomicInteger(0)
val builder = Thread.ofVirtual()
val threads = (1 to 1_000_000).map { n =>
builder.start(() =>
if Thread.currentThread().isVirtual then virtual.incrementAndGet()
sum.addAndGet(n.toLong)
)
}
threads.foreach(_.join())
println(sum.get())
println(virtual.get())
scala-cli run --server=false million.scala
500000500000
1000000
AtomicLong and AtomicInteger are the collections of this program that may be written from many threads at once: a plain var would lose increments and a plain counter would print a number that changes from run to run. A million threads are still a million objects, so the list holding them is the real cost here; a program that only needs the work done submits to Executors.newVirtualThreadPerTaskExecutor() and keeps no handle.
Related
- Execution contexts: the pool that turns a virtual thread into a future.
- Future and Promise: the promise the first program's task completes.
- Files and processes: the blocking calls a virtual thread is cheap for.
- Java: the same threads, from the language that introduced them.
Article author: Arthur Isaev