Reputation: 89613
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?
Upvotes: 6
Views: 3569
Reputation: 62652
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?
Upvotes: 3