Is there a stack space for every thread?

2020-08-13 08:00发布

问题:

If I understand correctly the stack is for local primities and references to the objects in the heap. So what happens if you have more than one threads?

Do they share the same stack space at the same time (but different areas) or does the JRE switch contexts and load-deload the stack content when switching between threads?

Or does the JRE allocate separate stacks for each threads?

回答1:

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.



回答2:

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.



回答3:

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".



回答4:

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.