Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a stack space for every thread?

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?

like image 864
breakline Avatar asked May 16 '15 00:05

breakline


3 Answers

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

like image 88
Arian Kiehr Avatar answered Oct 19 '22 00:10

Arian Kiehr


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.

like image 42
Stephen C Avatar answered Oct 18 '22 23:10

Stephen C


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.

like image 3
Radiodef Avatar answered Oct 18 '22 23:10

Radiodef