Video in progress

What does the -Xss flag configure, and when do you have to change it?

-Xss sets the size of each thread's stack. You can raise it for deep recursion, or lower it to save memory when there are very many threads.

📖 Answer

On 64-bit Linux the default thread stack is usually 1 MB. It is written like this:

java -Xss512k -jar app.jar

When you have to raise it: a recursive algorithm (a parser, a tree walk) works correctly but is deep and throws StackOverflowError.

Lowering it is useful when the application has thousands of platform threads: each asks for 1 MB of virtual memory, and 2000 threads need 2 GB for stacks alone.

What to know:

  • -Xss affects all threads. If you need a different size for one thread, there is the new Thread(group, task, name, stackSize) constructor;
  • stack memory is not part of the heap, and -Xmx doesn't count it;
  • Java 21 virtual threads store their stacks on the heap in small chunks, so for them this problem almost disappears.