简体   繁体   中英

Why is there no method to get the actual size of the stack?

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?

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

  • Local Variables of type byte, char, int, long, float, double the longest of these are double which is 8 bytes
  • References to objects are 4 bytes on 32 bit vm, 8 bytes on 64 bit vms (possibly shorter, 48 bit references are used to save space)

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM