Java stack size myths
How Java uses the stack mostly without documents. Therefore, we, the developers, stay with us. Today I wrote some interesting test codes that Results. For my tests, I used Sun JDK 1.5.0_12 under RedHat Enterprise Linux 3.
At first, I wanted to know the stack size that the VM chooses for threads. I found that the ulimit -s option does not directly affect the stack size selected by the virtual machine. The default is apparently 512kb, and can freely change with the -Xss and -XX: ThreadStackSize options. But I could not find a difference in behavior between these parameters. They seem to be doing the same. I further discovered that this Linux machine can create new threads at about 5000 per second.
I performed these tests by creating new threads and setting them to sleep in a blocking wait call immediately. I continued to create threads until the VM ran out of memory. With 512k stacks, the number of threads was about 3700, for 256k stacks about 7300, for 128k about 13700.
This leads to the following memory consumption by the stacks: 3700 x 512 kB = 1850 MB 7300 x 256 kB = 1825 MB 13700 x 128kB = 1713MB
Of course, a 32-bit process is limited to 4 GB of address space (minus 1 or 2 GB for the kernel). Therefore, it is only natural that memory is close to these 2GB minus heap size. (Note that Stack is never allocated from the heap.)
Next, I checked how deeply I can access the recursive method until I get a stack overflow. I did this by changing the original program, so that each thread will be returned to the method until it hits the overflow stack, then they fall asleep. The thread recorded maximum recursion depth. That I got really strange results. Especially with a VM server, the maximum depth varies over a wide range between 1750 and 5700 calls (128 thousand Stacks)! It is far from constant that was my first guess. With a client VM, the number is usually lower but does not vary so much: between 1100 and 1650.
Also, the maximum depth is apparently lower at the beginning of the test and increases towards the end.