Is there a stack space for every thread?

吃可爱长大的小学妹 提交于 2019-12-05 01:38:08

Or does the JRE allocate separate stacks for each threads?

Conceptually yes. (See this JVM spec link, for example.)

How the spec's conceptualization gets implemented in a particular JVM is ... implementation specific. However, my understanding is that current generation (e.g. Hotspot) JVMs allocate each thread stack in a separate block of memory requested from the OS; e.g. using a mmap syscall1.

There is certainly no wholesale copying of stack content when a thread switch occurs. However thread context switching does entail saving and loading registers, and (indirectly) to extra load on memory cache and TLB entries. This can be significant ... which is why excessive thread context switches (e.g. caused by lock contention or excessive wait/notify) can be bad for performance.


1 - My recollection is that some JVMs include a read-only "red-zone" page at the end of each stack segment. (This means that thread stack overflow triggers a memory fault, and the JVM doesn't need to explicitly check for stack overflow on each method call, which would be a significant performance hit.) Anyhow, my understanding is that the "red-zone" page requires the thread stacks to be requested using mmap.

Or does the JRE allocate separate stacks for each threads?

Yes. The JVM is specified to do so:

Each Java Virtual Machine thread has a private Java Virtual Machine stack, created at the same time as the thread. A Java Virtual Machine stack stores frames. [...] Because the Java Virtual Machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated.

Each thread has its own stack that holds a frame for each method executing on that thread as you can see here in the section "Per Thread".

Java threads are represented by thread objects, each thread is assigned a separate thread stack used for storing runtime data. The thread stack has a specific size (Can be set using VM option java -Xss1m Application).

If during runtime, the Thread tries to store more date than the stack size allows, a stack overflow error occurs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!