Sub topic 1
Platform Threads: What Java Threads Have Always Been
Platform Threads
A thread is a path of work that runs inside your program. For most of Java's history, each Java thread was a platform thread. A platform thread is a Java thread that wraps one thread of the operating system (OS). The OS decides when that thread runs.
OS threads are expensive. Each one reserves memory for its stack, often about 1 MB. Creating one and switching between threads also takes time. Because of this, a normal computer can only run a few thousand platform threads.
Why Thread-per-Request Runs Out of Threads
Many servers use thread-per-request. Thread-per-request is a style where each incoming request gets its own thread for its whole life. This style is easy to read and debug.
Most requests spend their time waiting for a database, a file, or another server. While a platform thread waits, it still holds its memory and its OS thread. With 10,000 waiting users you need 10,000 platform threads, and the server runs out of them long before the CPU is busy.
Meet Virtual Threads
A virtual thread is a lightweight Java thread that the JVM manages instead of the OS. Virtual threads became a final feature in Java 21 (JEP 444). Each one costs very little memory, so you can create millions of them.
When a virtual thread waits, the JVM moves it off the OS thread. That OS thread can then run other work.
Creating Your First Virtual Threads
Java has a builder for each kind of thread. Thread.ofVirtual() makes virtual threads, and Thread.ofPlatform() makes platform threads. Thread.startVirtualThread() is a shortcut that creates a virtual thread and starts it in one step.
public class StartVirtual {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.startVirtualThread(() -> System.out.println("Hello from a virtual thread"));
t.join();
Thread named = Thread.ofVirtual().name("hello-vt").start(() ->
System.out.println("virtual = " + Thread.currentThread().isVirtual()));
named.join();
Thread platform = Thread.ofPlatform().start(() -> System.out.println("Hello from a platform thread"));
platform.join();
}
}The join() method waits until the thread finishes. isVirtual() returns true for a virtual thread.
Exercise
Why can a server run far more virtual threads than platform threads?
Show answer
Each platform thread holds an expensive OS thread and its memory, even while it waits. A virtual thread is managed by the JVM, uses little memory, and gives up its OS thread while it waits.
Exercise
Which method creates and starts a virtual thread in a single call?
Show answer
Thread.startVirtualThread().