Each thread's own stack
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Threads in one JVM share a single heap, but each thread runs its own chain of method calls, so each one needs its own stack. That one fact explains why local variables never need locks, why a shared object does, and why ten thousand threads can be either a problem or no problem at all.
Every platform thread gets its own stack
A platform thread is a Java thread backed by one operating-system thread; every new Thread(...) creates one. When it starts, the JVM gives it its own JVM stack, and the thread keeps that stack until it ends.
Example 1 · Three threads, three stacks
import java.util.List;
public class OwnStackDemo { static List<String> frames() { return StackWalker.getInstance().walk(s -> s .filter(f -> f.getClassName().equals("OwnStackDemo")) .filter(f -> !f.getMethodName().startsWith("lambda$")) .map(StackWalker.StackFrame::getMethodName) .toList()); }
static void countTickets(String counter, int people) { int sold = 0; // a local: one copy per call, per thread for (int i = 0; i < people; i++) { sold++; } System.out.println(counter + " on " + Thread.currentThread().getName() + ": sold " + sold + ", stack " + frames()); }
public static void main(String[] args) throws InterruptedException { Thread platform1 = new Thread(() -> countTickets("Counter 1", 120), "t1"); Thread platform2 = new Thread(() -> countTickets("Counter 2", 75), "t2");
platform1.start(); platform1.join(); platform2.start(); platform2.join();
countTickets("Counter 3", 40); // runs on the main thread }}Counter 1 on t1: sold 120, stack [frames, countTickets] Counter 2 on t2: sold 75, stack [frames, countTickets] Counter 3 on main: sold 40, stack [frames, countTickets, main]
What this code does
- All three calls run the same
countTicketscode, but each one has its ownsoldin its own frame, so the counts never mix. - The stacks differ: on
t1andt2the bottom frames are the thread's own start-up (the lambda, filtered out here), while onmainthe frame belowcountTicketsismain. Each thread started with an empty stack of its own.
Every call the thread makes pushes a frame on its own stack only. When two threads run the same method, each pushes its own frame with its own parameters and locals. The method's code is shared, because it lives with the class in Metaspace (and in the code cache once compiled); the frames are not.
Stack size and the -Xss option
-Xss sets the stack size of new threads, for example java -Xss512k App or java -Xss2m App. On HotSpot with 64-bit Windows or Linux the default is 1 MB.
Example 2 · How deep can calls go?
public class StackDepthDemo { static int depth = 0;
static void goDeeper() { depth++; goDeeper(); // no base case: runs until this thread's stack is full }
static int measure() { depth = 0; try { goDeeper(); } catch (StackOverflowError e) { // the stack is full; the frames are popped as the error travels back here } return depth; }
public static void main(String[] args) throws InterruptedException { System.out.println("main thread: " + measure() + " calls deep");
for (long kb : new long[]{256, 4096}) { Thread t = new Thread(null, () -> System.out.println(kb + " KB stack: " + measure() + " calls deep"), "worker-" + kb, kb * 1024); t.start(); t.join(); } }}main thread: 30021 calls deep 256 KB stack: 13066 calls deep 4096 KB stack: 258860 calls deep
What this code does
- Each
goDeepercall adds a frame until the thread's stack is full and the JVM throwsStackOverflowError. The bigger requested stack allows far more calls. This program catches the error only to measure the depth; the lesson on StackOverflowError explains why you normally do not. - The numbers change between runs and machines. On the same laptop, another run printed 23396, 5234 and 103520, because early calls run in the interpreter with bigger frames and later calls run JIT-compiled code with smaller ones.
- Running
java -Xss256k StackDepthDemochanges the main thread's stack: one run reached only 3709 calls, whilejava -Xss2m StackDepthDemoreached 49667.
One thread can ask for its own size with the constructor Thread(ThreadGroup, Runnable, String, long stackSize), but the JDK documentation warns that some platforms ignore that value.
The stack size limits how deep calls can go, not how much data you can keep, because data lives on the heap. How many calls fit is not a fixed number: it depends on each frame's size, and a method running in the interpreter uses bigger frames than the same method after JIT compilation. So the depth changes from run to run.
-Xss only hides runaway recursion. If the depth grows with the input size, rewrite the recursion as a loop or use your own stack in a heap collection.Why local variables are thread-safe and heap objects are shared
Thread-safe means safe to use from many threads at the same time without extra care. Local variables are thread-safe, because they live in frames on one thread's private stack; no other thread can even see them.
Example 3 · Local counts are exact, the shared count is not
class SeatCounter { int booked = 0; // a field: lives in the shared object on the heap}
public class SharedCounterDemo { static final int BOOKINGS_PER_THREAD = 100_000;
public static void main(String[] args) throws InterruptedException { SeatCounter shared = new SeatCounter(); int[] perThread = new int[2];
Runnable job0 = () -> { int mine = 0; // local: private to this thread for (int i = 0; i < BOOKINGS_PER_THREAD; i++) { mine++; shared.booked++; // read, add 1, write back: not atomic } perThread[0] = mine; }; Runnable job1 = () -> { int mine = 0; for (int i = 0; i < BOOKINGS_PER_THREAD; i++) { mine++; shared.booked++; } perThread[1] = mine; };
Thread a = new Thread(job0); Thread b = new Thread(job1); a.start(); b.start(); a.join(); b.join();
System.out.println("Local counts: " + perThread[0] + " + " + perThread[1] + " = " + (perThread[0] + perThread[1])); System.out.println("Shared object: " + shared.booked); }}Local counts: 100000 + 100000 = 200000 Shared object: 162221
What this code does
- Each thread's
mineis a local in its own frame, so both reach exactly 100000. The two lambdas write to different array slots, andmainreads them only afterjoin. shared.bookedis one field in one heap object. Both threads runbooked++at the same time and many updates are lost, so the total is below 200000 and changes every run (162221 here, 160356 in the next run).
Heap objects are shared: any thread holding a reference can read and change the same object at the same moment. booked++ on a field is really three steps, read, add 1 and write back, so two threads can read the same old value and one update is lost. A local reference does not make its object private: if two threads' locals point to one object, that object is still shared. The Multithreading and Concurrency section covers the fixes, such as synchronized and AtomicInteger.
Memory cost of many threads
Each platform thread costs native memory outside the heap: its stack plus some JVM and operating-system bookkeeping. With 1 MB stacks, 200 threads reserve about 200 MB of address space.
Example 4 · Two hundred waiting threads
import java.lang.management.ManagementFactory;import java.util.ArrayList;import java.util.List;import java.util.concurrent.CountDownLatch;
public class ManyThreadsDemo { public static void main(String[] args) throws InterruptedException { int count = args.length > 0 ? Integer.parseInt(args[0]) : 200; int holdSeconds = args.length > 1 ? Integer.parseInt(args[1]) : 0; CountDownLatch release = new CountDownLatch(1); List<Thread> waiters = new ArrayList<>();
System.out.println("Live threads before: " + ManagementFactory.getThreadMXBean().getThreadCount()); for (int i = 0; i < count; i++) { Thread t = new Thread(() -> { try { release.await(); // each thread waits here, keeping its stack } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); t.start(); waiters.add(t); } System.out.println("Live threads now: " + ManagementFactory.getThreadMXBean().getThreadCount());
Thread.sleep(holdSeconds * 1000L); // time to look at the process with jcmd release.countDown(); for (Thread t : waiters) { t.join(); } System.out.println("All " + count + " waiting threads finished"); }}Live threads before: 7 Live threads now: 207 All 200 waiting threads finished
What this code does
- Each new platform thread waits on the latch, so all 200 are alive at once and each holds its own stack. The 7 threads before are
mainplus JVM helper threads; the count differs between JVMs. - The optional second argument keeps the threads waiting for that many seconds, so you can inspect the process from another terminal as in Example 5.
Example 5 · Reserved versus committed stack memory
# Terminal 1: 200 waiting threads, held for 12 secondsjava -XX:NativeMemoryTracking=summary ManyThreadsDemo 200 12# Terminal 2: while they waitjcmd <pid> VM.native_memory summary scale=MB...
- Thread (reserved=228MB, committed=15MB)
(threads #227)
(stack: reserved=227MB, committed=14MB, peak=14MB)
...What this code does
- Trimmed real output from Java 21 on 64-bit Windows. Native memory tracking counts 227 threads: the 200 waiters,
mainand the JVM's own threads, such as the garbage collector and JIT compiler threads. - The stacks reserve 227 MB, about 1 MB each, but only 14 MB is committed, about 60 KB per thread, because a waiting thread touches only the top of its stack.
Reserved is not the same as used: the operating system backs with real RAM only the stack pages a thread actually touches, which is called committed memory. An idle thread usually commits only tens of KB.
The limits still matter. Thousands of threads mean thousands of stacks, more work for the operating system to switch between them, and in the end OutOfMemoryError: unable to create native thread. That is why servers usually run a fixed-size thread pool instead of one new thread per request.
Java 21: virtual threads keep their stacks on the heap
A virtual thread (a final feature since Java 21) is a lightweight thread managed by the JVM instead of the operating system. Many virtual threads take turns on a small pool of platform threads called carrier threads.
Example 6 · Ten thousand virtual threads
// Java 21import java.util.ArrayList;import java.util.List;import java.util.concurrent.atomic.AtomicInteger;
public class VirtualThreadsDemo { static int checkSeat(int request, int depth) { if (depth == 0) { try { Thread.sleep(10); // blocks: the virtual thread is unmounted here } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return request % 2; } return checkSeat(request, depth - 1); // a few frames, so there is a stack to save }
public static void main(String[] args) throws InterruptedException { int requests = 10_000; AtomicInteger confirmed = new AtomicInteger(); List<Thread> threads = new ArrayList<>();
for (int i = 0; i < requests; i++) { int request = i; threads.add(Thread.ofVirtual().start(() -> { if (checkSeat(request, 20) == 0) { confirmed.incrementAndGet(); } })); } for (Thread t : threads) { t.join(); }
System.out.println("Virtual threads started: " + requests); System.out.println("Seats confirmed: " + confirmed.get()); System.out.println("Is a virtual thread? " + threads.get(0).isVirtual()); }}Virtual threads started: 10000 Seats confirmed: 5000 Is a virtual thread? true
What this code does
- Each request runs in its own virtual thread, 21 frames deep, and sleeps for 10 ms. While it sleeps it is unmounted and its frames wait on the heap, so a handful of carrier threads serve all 10,000.
- Proof from a run of this program with an 8-second sleep:
jmap -histo:live <pid>listed 10000jdk.internal.vm.StackChunkobjects using about 20 MB of heap, roughly 2 KB per waiting thread, compared with 1 MB reserved per platform thread. - The local
requestand the recursion'sdepthlive in each virtual thread's own frames; only theAtomicIntegeris shared, and it is updated safely.
While a virtual thread runs, its frames are on its carrier's stack.
When a virtual thread blocks, for example in Thread.sleep or while waiting for a database reply, HotSpot unmounts it: it copies the thread's frames into a stack chunk object on the heap and frees the carrier for another virtual thread. That stack is only as big as the calls it really holds, often a few KB, instead of a reserved 1 MB, so a server can keep tens of thousands of waiting requests.
Next step
Check your understanding
12 quick questions