Java / Java 21 Virtual Threads Interview questions
How does the JVM avoid exhausting memory with millions of virtual threads?
The key is where and how a thread's stack is stored. A platform thread reserves a fixed native stack - commonly around 1MB - at creation time, whether it's needed or not, and that memory sits outside the managed Java heap.
A virtual thread's stack instead starts tiny and lives inside its continuation object on the Java heap, growing and shrinking as call depth changes, and it's reclaimed by the garbage collector once the thread terminates like any other object.
So leaving thousands, or even millions, of virtual threads idle or blocked costs only bytes to low kilobytes each, rather than a full OS thread's reserved native stack and kernel-level bookkeeping. That structural difference, more than any single optimization, is what lets the JVM host so many virtual threads without exhausting memory.
More Related questions...