Are off-heap memory and Stack memory the same?

686 Views Asked by At

I know the difference between Stack and Heap memory however in many blogs I came across this word off-heap memory. I went through many blogs and youtube videos to find out if there is any relation between off-heap memory and Stack memory? According to the popular answer of this question, I can understand that the off-heap memory refers to store objects that are managed by EHCache and are not subjected to Garbage collection. This definition is perfect but my question is, is off-heap memory the same as Stack memory or its all together a different entity in the memory management?

Edit: If they are not same, could someone please explain in detail what makes them different with some basic explanation. I am quite new to the java memory management.

1

There are 1 best solutions below

0
On

They are not the same.

The differences:

  • stack memory is organized as a stack that tracks method call lifetimes, but off-heap memory is not
  • stack memory is allocated and freed implicitly1 when methods are called and when they return2, but off-heap memory is allocated and freed by (typically) calls to native code.

That's all a typical Java developer needs to know. If you want to dig deeper, take a look at the OpenJDK source code.


1 - The stacks themselves are allocated implicitly by Thread.start() and freed when a thread terminates. They are a form of off-heap memory, but they need to be requested from the OS in order to implement the "red zone" that is typically used to detect stack overflow ...

2 - This ignores the fact that when "escape analysis" is enabled, the JIT may generate code that allocates local objects onto the stack. If that happens, then the notional allocation and releasing of stack memory may happen within a method call.