2

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.

Alex Raj Kaliamoorthy
  • 2,035
  • 3
  • 29
  • 46
  • 1
    This is a duplicate of https://stackoverflow.com/questions/6091615/difference-between-on-heap-and-off-heap (in which at least one answer gives the answer to this question, which is no). I can't vote to close because I accidentally retracted my initial close vote. – JeremyP Apr 17 '18 at 14:19
  • Its not a duplicate question. I am not asking the difference between on-heap and off-heap memory or my question is in finding the difference between stack and heap memory. The question is to understand whether off-heap memory and Stack memory are same or not? – Alex Raj Kaliamoorthy Apr 17 '18 at 14:20
  • This answer https://stackoverflow.com/a/13894476/169346 to that question tells you everything you need to know. The answer is "no they are not the same". – JeremyP Apr 17 '18 at 14:23
  • @JeremyP, thanks for your tip. I have updated my question and if you could review and put your comments, would be great. – Alex Raj Kaliamoorthy Apr 17 '18 at 14:31

1 Answers1

3

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216