Stack vs Heap memory in Java

Preetham Umarani
2 min readAug 9, 2021

In order to run an application optimally, Java/JVM divides memory into stack and heap memory.

  • declare new variables
  • call new method
  • declare String or perform operations
  • create an object

JVM designates memory to these operations from either stack or heap space.

Stack memory:

Stack memory in java is used for static memory allocation and execution of a thread. Basically each thread calls methods, and each method is created on stack as a block and all the variables and objects references from heap would be stored. Access to this memory is LIFO(Last in first out).

So each method is created on top of stack and latest method would be popped out with completion of each method execution and space is available for the next method.

Key Features of the Stack memory:

Following key features:

  • It’s elastic memory
  • Variables and references exists in stack frame only till the method that created them is running
  • It’s allocated and deallocated when method finishes execution
  • If this memory is full and java throws java.land.StackOverFlowError
  • Access to this memory is fast when compared to Heap
  • This memory is thread-safe as each thread operates in its own stack

Heap Space in java:

Heap space in Java for dynamic memory allocation for Java objects and JRE classes at the runtime. New objects are always created in heap space and the references to this objects are stored in stack memory.

These objects have global access and can be accessed from anywhere in the application.

This memory model is further broken into smaller parts called generations.

  • Young generation — for new objects are allocated and aged. A minor garbage collection occurs when this fills up.
  • Old or Tenured Generation — This is where long surviving objects are stored. When objects are stored in young generation, a threshold for the object’s age is set and when that threshold is reached, the object is moved to the old generation.
  • Permanent Generation — This consists of JVM metadata for the runtime classes and application methods.

Key features of java heap memory:

  • It’s accessed via complex memory management techniques that include young generation, old or tenured generation and permanent generation.
  • If heap space is full, java throws java.lang.OutOfMemoryError
  • Access is quiet slower than stack memory
  • This memory, in contrast to stack, isn’t automatically deallocated. It needs Garbage collector to free up unused objects so as to keep efficiency of the memory usage.
  • Unlike stack, a heap isn’t thread-safe and needs to be guarded by properly synchronising the code.

--

--