I understand that there is no way to get the stack size of a thread in Java at runtime (see Can one obtain actual stack size used by a thread in Java after some time of running?).
For example, if we create a java.lang.Thread specifying a stack size of 64*1024, the JVM is free to give us a thread with any stack size.
However, I believe that actually knowing the actual size of the stack is very useful for certain applications which requires this kind of information.
What is the reason that we do not have a method which tells us the actual number of bytes used for the stack?
Is there some kind of limitation in the architecture that makes it impossible to get the actual number of bytes for a thread?
size() method in Java is used to get the size of the Stack or the number of elements present in the Stack. Parameters: The method does not take any parameter. Return Value: The method returns the size or the number of elements present in the Stack.
According to the algorithm, a stack is a discrete memory region of fixed size.
Size of a stack is the number of items present in a stack at a particular instant. Consider the below stack. It contains four items i.e. 5, 7, 4, 10. Therefore the size of the stack is 4.
In Visual Studio the default stack size is 1 MB i think, so with a recursion depth of 10,000 each stack frame can be at most ~100 bytes which should be sufficient for a DFS algorithm. Most compilers including Visual Studio let you specify the stack size.
The only things that are stored on the stack are primitive types and references. Objects are always created on the heap, so the data types that would be stored on the stack are
Note that arrays are objects types so they are stored on the heap, also if you have a primitive that is a field in a class then the primitive is part of an object and therefore will be stored on the heap.
So its pretty hard to run out of stack space for a thread unless you have runway recursion. I would imagine that is the reason why the Java designers don't give you a way to find out the stack size.
Another reason not to give the stack size is that it would be an implementation details that you can't really do anything with, you can't change the size of a thread stack after you have created the thread, and you can't do pointer arithmetic so what the point of knowing the stack size?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With