Is there a stack space for every thread?
Asked Answered
H

4

12

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?

Hardship answered 16/5, 2015 at 0:40 Comment(0)
C
6

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

Captious answered 16/5, 2015 at 1:19 Comment(0)
S
4

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

Sybil answered 16/5, 2015 at 0:47 Comment(0)
I
3

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.

Invaluable answered 16/5, 2015 at 0:52 Comment(0)
J
1

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.

Joselyn answered 16/5, 2015 at 1:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.