1. Overview
In this quick tutorial, we’re going to see how to configure the thread stack sizes in the HotSpot JVM.
2. Default Stack Size
Each JVM thread has a private native stack to store call stack information, local variables, and partial results. Therefore, the stack plays a crucial part in method invocations. This is part of the JVM specification, and consequently, every JVM implementation out there is using stacks.
However, other implementation details, such as stack size, are implementation-specific. From now on, we’ll focus on the HotSpot JVM and will use the terms JVM and HotSpot JVM interchangeably.
Anyway, the JVM will create stacks at the same time it creates the owning thread.
If we don’t specify a size for the stacks, the JVM will create one with a default size. Usually, this default size depends on the operating system and computer architecture. For instance, these are some of the default sizes as of Java 14:
- Linux/x86 (64-bit): 1 MB
- macOS (64-bit): 1 MB
- Oracle Solaris (64-bit): 1 MB
- On Windows, the JVM uses the system-wide stack size
Basically, we can expect around 1 MB for each stack in most modern operating systems and architectures.
3. Customizing the Stack Size
To change the stack size, we can use the -Xss tuning flag. For example, the -Xss1048576 sets the stack size equal to 1 MB:
java -Xss1048576 // omitted
If we don’t want to calculate the size in bytes, we can use some handy shortcuts to specify different units — the letter k or K to indicate KB, m or M to indicate MB, and g or G to indicate GB. For example, let’s see a couple of different ways to set the stack size to 1 MB:
-Xss1m
-Xss1024k
Similar to -Xss, we can also use the -XX:ThreadStackSize tuning flag to configure the stack size. The syntax for -XX:ThreadStackSize, however, is a bit different. We should separate the size and the flag name with an equal sign:
java -XX:ThreadStackSize=1024 // omitted
The HotSpot JVM won’t allow us to use a size less than a minimum value:
$ java -Xss1K -version
The Java thread stack size specified is too small. Specify at least 144k
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Also, it won’t allow us to use a size more than the max value (usually 1 GB):
$ java -Xss2g -version
Invalid thread stack size: -Xss2g
The specified size exceeds the maximum representable size.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
4. Conclusion
In this quick tutorial, we saw how to configure the thread stack sizes in the HotSpot JVM.