Tuesday, July 27, 2021

Difference between Stack and Heap memory in Java? Example

The difference between stack and heap memory is a common programming question asked by beginners learning Java or any other programming language. Stack and heap memory are two terms programmers start hearing once they started programming but without any clear and definite explanation. Lack of knowledge of what is a heap in Java and what is stack memory in Java results in misconceptions related to stack and heap. To add to this confusion, a stack is also a data structure that is used to store elements in LIFO(Last In First Out) order and is available in Java API as java.util.Stack.

In general, both stack and heap are part of memory, a program is allocated and used for different purposes. Java program runs on JVM which is launched as a process by the "java" command. Java also uses both stack and heap memory for different needs. 

In our last article 10 points on Java heap space, I have touched base on Java heap space, and in this article, we will see the difference between stack and heap memory in Java.



Difference between Stack vs Heap in Java

Here are a few differences between stack and heap memory in Java:



1) The main difference between heap and stack is that stack memory is used to store local variables and function calls while heap memory is used to store objects in Java. No matter, where the object is created in code e.g. as a member variable, local variable, or class variable,  they are always created inside heap space in Java.


2) Each Thread in Java has its own stack which can be specified using the -Xss JVM parameter, similarly, you can also specify the heap size of the Java program using JVM option -Xms and -Xmx where -Xms is starting size of the heap and -Xmx is a maximum size of java heap. to learn more about JVM options see my post 10 JVM option Java programmers should know.

Difference between Stack and heap memory in Java - interview question

3. If there is no memory left in the stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space. Read more about how to deal with java.lang.OutOfMemoryError  in my post 2 ways to solve OutOfMemoryError in Java.


4) If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is a lot lesser than the size of heap memory in Java.


5) Variables stored in stacks are only visible to the owner Thread while objects created in the heap are visible to all threads. In other words, stack memory is a kind of private memory of Java Threads while heap memory is shared among all threads.


That's all on the difference between Stack and Heap memory in Java. As I said, It’s important to understand what is a heap and what is stack in Java and which kind of variables goes where, how you can run out of stack and heap memory in Java, etc. Let us know if you are familiar with any other difference between stack and heap memory in java.

18 comments :

Javin @ Garbage collection in Java said...

Good question Keul. I think Garbage collector only collect Heap memory. Since object is only created in heap and stack mostly contains local variable which gets wiped off once they lost scope.

nlotz said...

The stack contains only values for integral types and references to objects, which are always stored in the heap. Since it doesn't contain any objects itself, there would be nothing to garbage-collect.

Erwin Müller said...

For me it would be interesting to know where variables are stored that are references to objects. For example: I create a new Object:
foo = new Object()

The object itself is stored on the heap. But what about the reference to the object?

Like in C, you have the memory of the object and the pointer or reference to that memory:
foo = malloc(sizeof(Struc));

It wouldn't make much sense to store the reference on the heap, if the reference is a local variable or a parameter.

Keul said...

@nlotz i think not only integral type but all predefined data type or we can say primitive types and all method calls are stored in Stack..

Anonymous said...

"No matter, where object is created in code e.g. as member variable, local variable or class variable, they are always created inside heap space in Java."

This is inaccurate. Escape analysis was introduced in 6u14 and enabled by default in 6u23.

"The -XX:+DoEscapeAnalysis option directs HotSpot to look for objects that are created and referenced by a single thread within the scope of a method compilation. Allocation is omitted for such non-escaping objects, and their fields are treated as local variables, often residing in machine registers. Synchronization on non-escaping objects is also elided."

http://www.oracle.com/technetwork/java/javase/6u14-137039.html

"Escape analysis is supported and enabled by default in Java SE 6u23 and later."

http://docs.oracle.com/javase/7/docs/technotes/guides/vm/performance-enhancements-7.html

Vivek Hingorani said...

Great Article.. Your blog is full of useful information

Pavan S said...

Very informative and as someone said above it is good refresher.. thanks for sharing information.

pranathi said...

Very informative ....thank u :) I have one doubt regarding stack. How Runtime stacks (stack created by each thread) share same memory?

TARUN said...

Very good and answered my question about difference bw stack and heap. Keep up the good work...

Sachindra N. Pandey said...

Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
Objects stored in the heap are globally accessible whereas stack memory can’t be accessed by other threads.
Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc, more details at Java Garbage Collection.
Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.
We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.
When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.

Anonymous said...

Is this actual for java 8?

Sachindra N. Pandey said...

Informative :)

Deepak Kumar said...

learnt something new.
thanks for sharing.

Unknown said...

Awesome posts. Kudos.... :)

Unknown said...

Perfect description. Easy to understand. Thanks

Anonymous said...

Good description.Thank you.

Anonymous said...

Can you please explain use of heap and stack memory with programming example? It would be more clearer then.

Anonymous said...

An example to generate java.lang.OutOfMemoryError in java:

public class Error {
public static void main(String[] args) {
List lista = new ArrayList();
String concat = "";
while (true) {
concat += ""+UUID.randomUUID();
lista.add(concat);
}
}
}

Post a Comment