简体   繁体   English

为什么没有方法来获得堆栈的实际大小?

[英]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? ). 我知道在运行时没有办法在Java中获取线程的堆栈大小(参见可以在运行一段时间后获得Java中线程使用的实际堆栈大小吗? )。

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. 例如,如果我们创建一个指定堆栈大小为64 * 1024的java.lang.Thread ,JVM可以自由地为我们提供任何堆栈大小的线程。

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 类型为byte,char,int,long,float,double的局部变量是double中最长的两倍,即8个字节
  • 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) 对象的引用是32位vm上的4个字节,64位vms上的8个字节(可能更短,48位引用用于节省空间)

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. 我想这就是Java设计师没有给你一种方法来找出堆栈大小的原因。

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? 不给出堆栈大小的另一个原因是它将是一个实际的细节,你无法真正做任何事情,你不能在创建线程后改变线程堆栈的大小,你不能做指针算术那么知道堆栈大小有什么意义呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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