Java specification告诉我们有关于线程堆栈的一些事情.除其他事项外:

>每个Java虚拟机线程都有一个私有Java虚拟机堆栈,与线程同时创建.

>因为除了推送和弹出帧之外,永远不会直接操作Java虚拟机堆栈,因此可以对堆进行堆分配. Java虚拟机堆栈的内存不需要是连续的.

>规范允许Java虚拟机堆栈具有固定大小或根据计算要求动态扩展和收缩.

现在,如果我们专注于像HotSpot这样的JVM实现,我们可以获得更多信息.以下是我从不同来源收集的一些事实:

> HotSpot中线程的最小堆栈大小似乎是固定的.这就是前面提到的-Xss选项.

(Source)

In Java SE 6, the default on Sparc is 512k in the 32-bit VM, and 1024k in the 64-bit VM. … You can reduce your stack size by running with the -Xss option. …

64k is the least amount of stack space allowed per thread.

> JRockit分配与堆栈所在的堆分开的内存. (Source)

Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.

>在HotSpot中,Java线程和本机OS线程之间存在直接映射. (Source).

>但HotSpot中的Java线程堆栈是软件管理的,它不是OS本机线程堆栈. (Source)

It uses a separate software stack to pass Java arguments, while the native C stack is used by the VM itself. A number of JVM internal variables, such as the program counter or the stack pointer for a Java thread, are stored in C variables, which are not guaranteed to be always kept in the hardware registers. Management of these software interpreter structures consumes a considerable share of total execution time.

> JVM还为本机方法和JVM运行时调用(例如类加载)使用相同的Java线程堆栈. (Source).

>有趣的是,即使分配的对象有时可能位于堆栈上而不是堆上,作为性能优化. (Source)

JVMs can use a technique called escape analysis, by which they can tell that certain objects remain confined to a single thread for their entire lifetime, and that lifetime is bounded by the lifetime of a given stack frame. Such objects can be safely allocated on the stack instead of the heap.

因为一张图片胜过千言万语,所以这是从James Bloom

开始的

现在回答你的一些问题:

How does JVM knows how may threads will be created?

它没有.通过创建可变数量的线程可以很容易地通过矛盾来证明.它确实对每个线程的最大线程数和堆栈大小做了一些假设.这就是为什么如果分配太多线程,你可能会耗尽内存(不是指堆内存!).

Does Java create a stack for each thread when it is created?

如前所述,每个Java虚拟机线程都有一个私有Java虚拟机堆栈,与线程同时创建. (Source).

If so, where exactly the stack is on the memory? It is certainly not in the “managed” heap.

如上所述,从技术上讲,Java specification允许堆栈存储器存储在堆上.但至少JRockit JVM使用不同的内存部分.

Does JVM create stack from native memory or does it pre-allocate a section of managed memory area for stack?

堆栈是JVM管理的,因为Java规范prescribes它必须如何运行:Java虚拟机堆栈存储帧(第2.6节). Java虚拟机堆栈类似于传统语言的堆栈.一个例外是用于本机方法的Native Method堆栈.更多关于这一点在the specification年.