Heap vs Stack memory in Java

Very first lets look at what is stack and heap and finally we can explain how Java JVM allocate memory in those two areas. 

Stack

Stack stores temporary variables created by a function/block. In stack, variables are declared, stored and initialized during runtime. This is not a long term or permanent memory and when function exist memory will be deleted. Specially stack is responsible to manager local variables, reference variables and methods. This is physical RAM and StackOverFlowError error comes when memory is not enough in java JVM. This has LIFO machisam. 

Heap

Heap is to store global variables. All global variables are stored in heap memory space. It supports Dynamic memory allocation. In Java heap is created wheneven JVM is initializing . And heap will be up and running until the program exists. And memory should be managed by programmer. Unless garbase collector will clear unusing objects from memory. Unlike stack , heap allocate memory dynamically , not in order. All elements of heap memory can be accessed from any threads , so it is public. 

There are few memory areas inside heap memory. 

Young generation

Yound generation space is the place for fresh objects in heap. This space be devide in to two parts such as :-

01. Eden Space 

When a new object create from new keyword that object will be saved in  this area. 

 

02. Survivor Space

Any object survied from eden space belongs to here. This is also has two sections such as S0 and S1

Old generation

This pool basically contains tenured and virtual space and will be holding those objects which survived after garbage collection from Young Generation.
 

Permanent generation

This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members.

 

Code Cache

Code cache area is containing memory which will be used for compilation and storage of native code

 

References :-

https://www.javatpoint.com/stack-vs-heap-java

https://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/garbage_collect.html

https://stackoverflow.com/questions/2129044/java-heap-terminology-young-old-and-permanent-generations

https://www.guru99.com/stack-vs-heap.html

Leave a Reply