Alexey Osetsky
Alexey Osetsky

Reputation: 178

Stack is part of the heap or is it separate memory

I was looking at the documentation

Also found a picture with a memory structure on baeldung

enter image description here

I learned from the documentation that:

Each Java Virtual Machine thread has a private Java Virtual Machine stack, created at the same time as the thread

But I cannot understand: Is the Stack part of the heap or is it separate memory?

Upvotes: 1

Views: 1117

Answers (1)

Stephen C
Stephen C

Reputation: 719159

Is the Stack part of the heap or is it separate memory?

The JVM specification does not say. So in theory it would be possible to implement a JVM where thread stacks are in the heap or in separate (non-heap) memory.

In practice, all JVMs based on the mainstream Sun, Oracle and OpenJDK codebases use separate (non-heap) memory for thread stacks. One reason is that it simplifies the JVM's memory management if stacks cannot be relocated by the garbage collector.

But the flipside is that it makes no difference1 to Java programs which approach a particular Java implementation has taken.


1 - Apart from questions like "do I need to increase the heap size to run more threads ...".

Upvotes: 3

Related Questions