Difference between Heap and Stack Memory in Java? [Explained]

One of the many traits of a good programmer is how well he understands the fundamentals and if you want to check the fundamentals of a Java programmer then asking the difference between heap and stack memory is a good choice. Even though both are part of JVM and both consumer's memory allocated to the Java process, there are many differences between them like Heap memory is shared by all threads of Java application but Stack memory is local to each thread. Objects are created in heap memory but method frames are stored in Stack memory, and the size of heap space is much bigger than the small size of Stack in Java.

Even if you know this much information about heap and stack in Java, you are one of the better candidates, but let's see some more details to impress the interviewer.

Btw, If you are serious about mastering JVM and Java performance in-depth then you can also check out this Udemy best-selling course - Java Application Performance and Memory Management course by Matt Greencroft. It's a great course for experienced Java developers.


Difference between Stack vs Heap in Java

As I told you, both Stack and Heap space are part of JVM but they are used for a different purpose, let's see some more points to understand the difference between stack and heap memory better.

1. Size

One of the significant differences between Stack and heap comes from their size. Heap space in Java is much bigger than the Stack memory. This is partly due to the fact that whenever a new thread is created in JVM, separate stack memory is allocated to them.

2. Resizing

JVM allows you to resize both heap and stack in Java, though you need to use different JVM flags for that. You can use -Xms and -Xmx to specify the starting and maximum heap memory in Java. Similarly, you can use the -Xss to specify the stack size of individual threads in JVM.

If you want to learn more, you can further check out Java Memory Management course on Udemy to learn about memory management and  JVM tuning in Java.




3. Usage

Another significant difference between heap and stack memory comes from their usage perspective. Heap memory is used to store objects in Java. No matter where you create objects e.g. inside a method, a class, or a code block, they are always created in heap space and memory is allocated from the heap.

One little exception of that is String literals which live in String pool, which was not part of the heap until Java 7. Earlier String pool was created on PermGen space, which was separate memory are in JVM used to store class metadata, but from JDK 7 onwards String pool is merged into heap space.

On the other hand, Stack memory is used to store local variables e.g. primitive int and boolean variables, method frames, and call stack.

4. Visibility

One more difference between heap and stack memory comes from the visibility and sharing perspective. Heap memory is shared by all threads hence it is also known as the main memory but stack memory is local to threads and the local variable created there was not visible to others.

Threads can also cache values into Stack memory, which can sometimes cause issues, particularly if you are not aware of this behavior.

Btw, If you are writing mission-critical Java applications I suggest you spend some time learning JVM internals and if you need a course, Understanding the Java Virtual Machine: Memory Management By Kevin Jones on Pluralsight is a nice course.


Difference between Heap and Stack Memory in Java JVM


Though,  you would need a Pluralsight membership to access this course, which costs around $29 per month or $299 annually (14% discounted).  

If you don't have Pluralsight membership, I encourage you to get one because it allows you to access their 7000+ online courses on all the latest topics like front-end and back-end development, machine learning, etc. It also includes interactive quizzes, exercises, and the latest certification material.

It's more like Netflix for Software Developers and Since learning is an important part of our job, Pluralsight membership is a great way to stay ahead of your competition.

They also provide a 10-day free trial without any commitment, which is a great way to not just access this course for free but also to check the quality of courses before joining Pluralsight.

5. Order

Heap is a large memory area where objects can be created and stored in any order but Stack memory is structured as Stack data structure i.e. LIFO where method calls are stored as last in first out order. This is why you can use recursion in Java.


6. Heap and Stack Memory Errors

You get different errors when heap or stack memory gets filled. For example, a faulty recursive algorithm can quickly make Stack memory filled up with recursive method calls in that case you will see java.lang.StackOverFlowError.

But, when there is no more space left in heap to allocate a new object then you will see the OutOfMemoryError in java e.g. java.lang.OutOfMemoryError: Java Heap Space.

This is another useful difference to know between Stack and Heap in Java from debugging and troubleshooting perspective. If you like reading books, then you can also read Java Performance The Definitive Guide By Scott Oaks to learn more about heap and stack memory in Java.

stack vs heap in Java

This is one of my favorite books and I have read it a lot. Even though it's not updated in recent years and covers until Java 8, it still very valuable and probably the best book on the topic currently available in the market.

That's all about the difference between Stack and Heap memory in Java application. It's extremely important for any Java developer, fresher or experienced to know about these fundamentals. If you don't know about the heap, it would be very difficult to survive or clear any Java programming interviews.

Remember, stack memory is used to store local variables and methods calls while heap memory is used to store objects, also heap memory is much larger than stack memory but access to Stack is faster than the heap.


Other Java heap and JVM articles you may like
  • 7 Best Courses to learn JVM internals and GC (courses)
  • How to increase the heap size of the Java program running in Eclipse? (tutorial)
  • What is the difference between JIT and JVM? (answer)
  • Top 5 Courses to become a full-stack Java developer? (courses)
  • 10 Essential JVM options for a Java production system (article)
  • 5 Advanced books to learn JVM in-depth (books)
  • How to fix "could not create the Java virtual Machine invalid maximum heap size" (solution)
  • What is the maximum heap memory of 32-bit and 64-bit JVM? (answer)
  • Top 10 Courses to learn Java in-depth (courses)
  • How to get the max memory, free memory, and total memory in Java? (answer)
  • How to increase the heap memory of Maven and ANT? (tutorial)
  • What is the difference between direct, non-direct, and mapped byte buffer? (answer)
  • What is -XX:UseCompressedOops option in 64-bit JVM? (answer)
  • How Garbage Collection works in Java? (answer)
  • 10 Advanced Java courses for experienced programmers (courses)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are serious about mastering JVM and Java performance in-depth then you can also check out this Udemy best-selling course - Java Application Performance and Memory Management course by Matt Greencroft. It's a great course for experienced Java developers.

3 comments:

  1. "Earlier String pool was created on metaspace" - I think this is not true. Metaspace is a new memory area.

    ReplyDelete
    Replies
    1. "Earlier String pool was created on "Permgen Space" not Metaspace, I think there is a typo, I have fixed it now , thanks for pointing it.

      Delete

Feel free to comment, ask questions if you have any doubt.