问题
The JVM specification indicates the JVM stack can be either fixed size or dynamically expandable.
The -Xss JVM option allow to set the fixed size and if I am right not setting this option is setting a default value (around 512-2048k), but how can tell the JVM to dynamically allocate its stack when needed?
If I cannot set a dynamical size option, will setting a large -Xss value (let's say 20M) actually allocate 20MB of memory for each thread in my JVM or is it dynamically allocated memory that will be limited to 20MB?
回答1:
The maximum stack size is the amount of virtual address space that gets allocated to the stack. Memory is only committed to the stack as required.
Note that on 32-bit systems, virtual address space is a relatively scarce resource. You get less (sometimes much less) than 4GB per process. With this in mind, a 20MB stack would limit the number of threads to anywhere between 75 and 175.
回答2:
Regarding dynamic expansion, even though the specification may support it the implementation might not.
So, How to tell the JVM to dynamically allocate its stack when needed?
You Dont. You leave all settings as default and if the computation in a thread requires a larger stack than is permitted, the Java virtual machine throws a StackOverflowError.
This is your cue to use -Xss to explicitly increase memory allocation to new threads.
This does not affect the JVM Heap. [see -Xmx -Xms for setting heap size]
Also I must say, 20Mb seems slightly excessive per thread.
All depends on the size of your heap and the number of concurrent threads you would like to support.
来源:https://stackoverflow.com/questions/10456720/dynamically-expandable-jvm-stack