Tag Archives: stack

Java Memory Management

One topic that I have always been curious, is java memory management. How JVM allocates the memory to different objects and frees up the memory when needed? In this post, I will talk about Java Heap Memory and Stack Memory. Heap and Stack are the memories that JVM allocates as per the application requirements.

Java Heap Space

The most basic question that arises during this discussion, is how do you define both of these memories. So I will start with Java Heap Space. When JVM starts, it creates Java Heap Space and it is used by the application till the time the application is running. Java runtime uses heap space to allocate memory to objects and JRE classes.

The heap size is adjusted according to when the application runs. When the heap gets full, garbage collection takes place. During garbage collection, objects that are not being used, get cleaned, in-process making space for new objects.

Java Stack Memory

Stack memory is like a RAM, used by an executing thread for method-specific values or operations. Most of the values or operations in the stack are short-lived. It can also contain references to objects that reside in heap.

Whenever a method is invoked, a block is allocated in the stack for a method to hold local variables. The block gets cleared once the method finishes execution.

From these earlier definitions, it is clear that Stack memory is smaller in size compared to heap space.

Stack Memory and Heap Space

Differences between Heap space and Stack memory

  1. Heap memory is used by the entire application while the stack is used by execution thread only.
  2. When an object is created, it is stored in heap space, while the reference for that object is stored in stack memory.
  3. Since stack memory is thread-specific, it can’t be accessed by multiple threads or other threads than the one thread that created it. Heap space is global.
  4. Heap space is available till the time application is running, stack memory is short-lived.
  5. JVM can throw errors if both memories are full or the application doesn’t have either of memory remaining to continue running the application. StackOverfFowError if JVM is out of stack memory. If the application stops running provided there is no memory to store objects, it will throw OutOfMemoryError: Java Heap Space Error.

Conclusion

In this post, I discussed the differences between Java heap space and stack memory as part of Java memory management.

References

  1. Stack vs Heap
  2. Understanding memory management