Sub topic 1
Platform Threads: What Java Threads Have Always Been
Before you can see why virtual threads matter, you need a clear picture of the threads Java has used since version 1.0. Java now calls them platform threads. This chapter explains what they are, how they connect to the operating system, and what each one costs you in memory and time.
What a Thread Is
A thread is a single path of execution inside a program. It runs one instruction after another. A program with several threads can do several things at once, or at least appear to.
Every Java program starts with one thread, called main. When you create more threads, each one has its own call stack. A call stack is a block of memory that records which method is running, which method called it, and the local variables of each method.
Threads in the same program share the same heap. The heap is the memory where Java objects live. Because threads share the heap, two threads can read and change the same object.
Platform Threads Wrap Operating System Threads
A platform thread is a Java thread that is a thin wrapper around an operating system thread (OS thread). An OS thread is a thread that the operating system (Linux, Windows, macOS) creates, tracks, and schedules onto CPU cores.
The mapping is one to one. Every platform thread you start makes exactly one OS thread, and that OS thread belongs to your Java thread for its whole life. Java does not decide when your thread runs. The operating system's scheduler decides that. The scheduler is the part of the OS that picks which thread runs on which CPU core, and for how long.
In the diagram there are three threads but only two cores. The scheduler keeps switching between threads so that each one gets a turn.
Your First Platform Thread
The classic way to make a thread is new Thread(...). You pass it a Runnable, which is the code the thread should run. Calling start() asks the OS to create the real thread. Calling join() makes the current thread wait until the other thread finishes.
public class FirstPlatformThread {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
Thread current = Thread.currentThread();
System.out.println("Hello from " + current.getName()
+ ", virtual = " + current.isVirtual());
}, "my-worker");
worker.start();
worker.join();
System.out.println("Back in " + Thread.currentThread().getName());
}
}On JDK 21 or later the output is:
Hello from my-worker, virtual = false
Back in mainThe method isVirtual() returns false because this is a platform thread. Every thread you made before Java 21 was a platform thread, including the main thread and the threads inside thread pools.
Cost 1: Memory for the Stack
Each platform thread needs its own call stack, and the OS sets aside memory for it when the thread is created. On 64-bit Linux and macOS, the JVM's default stack size is 1 MB per thread. You can change it for all threads with the -Xss option, for example java -Xss512k MyApp.
That 1 MB is reserved, which means the address space is set aside. The OS only gives real physical memory as the stack actually grows. Even so, the reservation is fixed when the thread starts and cannot grow past its limit. If a thread calls methods too deeply, it runs out of stack and Java throws a StackOverflowError.
You can ask for a different stack size for one thread with a special constructor. The program below runs the same deep recursion on a small stack and on a large stack and prints how deep each one got.
public class StackDepth {
static int recurse(int depth) {
try {
return recurse(depth + 1);
} catch (StackOverflowError e) {
return depth;
}
}
static int measure(long stackSizeBytes) throws InterruptedException {
int[] result = new int[1];
Thread t = new Thread(null, () -> result[0] = recurse(0),
"stack-test", stackSizeBytes);
t.start();
t.join();
return result[0];
}
public static void main(String[] args) throws InterruptedException {
System.out.println("256 KB stack depth: " + measure(256 * 1024));
System.out.println("4 MB stack depth: " + measure(4 * 1024 * 1024));
}
}The exact numbers change from machine to machine and from run to run, but the bigger stack always gets much deeper. The JVM treats the stack size as a hint, and some platforms round it or ignore it.
The important point is this: each platform thread carries a stack of a fixed size, picked up front. If you want 10,000 threads, you must reserve 10,000 stacks.
Cost 2: Time to Create and Destroy
Starting a platform thread is not just making a Java object. The JVM must make a system call, which is a request to the operating system. The OS builds its own data structures, reserves the stack, and registers the thread with the scheduler. When the thread ends, all of that is torn down again.
Each step is quick, but it is far slower than calling a method. This program starts 2,000 platform threads, each of which sleeps for one second, and measures how long the work takes.
import java.util.ArrayList;
import java.util.List;
public class PlatformThreadCost {
public static void main(String[] args) throws InterruptedException {
int count = 2_000;
List<Thread> threads = new ArrayList<>();
long begin = System.nanoTime();
for (int i = 0; i < count; i++) {
Thread t = new Thread(() -> {
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
t.start();
threads.add(t);
}
long allStarted = System.nanoTime();
for (Thread t : threads) {
t.join();
}
long allFinished = System.nanoTime();
System.out.printf("Started %d threads in %d ms%n",
count, (allStarted - begin) / 1_000_000);
System.out.printf("All finished after %d ms%n",
(allFinished - begin) / 1_000_000);
}
}On a typical laptop, starting the threads takes from tens to a few hundred milliseconds. The total time is a little over one second, because all the threads sleep at the same time. While the program runs, the OS really does have about 2,000 extra threads. On Linux you can check this from another terminal with ps -o nlwp -p <pid>, which prints the number of OS threads in a process.
Because creating threads is slow, Java programs have long reused them through thread pools. A thread pool is a fixed group of threads that take tasks from a queue, one after another. Pools save creation time, but they also put a hard cap on how many tasks can run at once. The next chapter shows why that cap becomes a problem.
Cost 3: Context Switching
A CPU core runs one thread at a time. When the scheduler moves a core from one thread to another, it performs a context switch. A context switch means the OS saves the first thread's state (its registers and position in the code), then loads the second thread's state.
One context switch takes roughly a few microseconds. It also pushes useful data out of the CPU's caches, so the thread that runs next starts more slowly. With a few dozen threads this cost is small. With thousands of busy threads, the CPU can spend a real share of its time switching instead of doing your work.
Cost 4: Waiting Threads Still Cost the Same
Many threads spend most of their life blocked. A blocked thread is one that is waiting for something, such as a reply from a database, a file read, or the end of a sleep. While a platform thread is blocked, it does no work. Its OS thread and its stack still exist, though. The memory stays reserved and the OS still tracks the thread.
So a platform thread costs about the same whether it is computing or just waiting. This is the key weakness that virtual threads fix, and you will come back to it many times in this tutorial.
Summary of the Costs
| Cost | Where it comes from | Rough size |
|---|---|---|
| Stack memory | Fixed stack reserved per thread | About 1 MB reserved by default on 64-bit Linux and macOS |
| Creation and teardown | System call into the OS | Tens of microseconds or more per thread |
| Context switch | OS saves and loads thread state | A few microseconds, plus cache misses |
| Upper limit | OS and memory limits | Usually thousands to tens of thousands per process |
| Idle cost | Blocked threads keep their OS thread | Same memory as a busy thread |
Why Platform Threads Are Still Useful
None of this makes platform threads bad. They are a direct, well-tested link to the operating system. They are a good fit when you have a small number of long-running threads, or work that keeps the CPU busy, such as image processing or number crunching. In those cases you rarely want more threads than CPU cores anyway. Platform threads are not going away. Java 21 only added a second kind of thread alongside them.
Exercise
A program starts 5,000 platform threads, and each one spends 99% of its time blocked waiting for a network reply. Roughly how much stack memory is reserved, using the 64-bit Linux default, and why does the blocking not reduce this?
Show answer
About 5,000 × 1 MB, or roughly 5 GB of reserved stack address space. Blocking does not reduce it because each platform thread keeps its own OS thread and fixed stack for its whole life, whether it is running or waiting.
Exercise
In the FirstPlatformThread program, what changes if you replace worker.start() with worker.run()?
Show answer
No new thread is created. The lambda runs on the main thread, so it prints "Hello from main, virtual = false" instead of "my-worker". The join() call then returns at once because the worker thread was never started.
Exercise
Run StackDepth, then change the sizes to 128 KB and 16 MB. What pattern do you see, and what does it tell you about choosing one stack size for every platform thread?
Show answer
The larger stack reaches a much deeper recursion depth, roughly in proportion to its size, though the exact numbers vary. A single fixed size is always a trade-off. Too small risks StackOverflowError, and too large reserves memory that most threads never use, which limits how many threads you can create.