Lets see some of the main differences between Stack and Heap memory.
1) Stack memory is used to store local variables and references to other objects in the method whereas heap memory is used to store objects.
2) Size of heap memory is much bigger than the stack memory.
3) Each thread has their own stack which stores local variables and these variables are not accessible globally whereas objects stored in heap are globally accessible.
4) Heap memory size is bigger where we can create and store objects in any order whereas stack memory follows LIFO(Last In First Out) order.
5) We can change the size of heap memory using jvm parameters : -Xms for initial heap memory and –Xmx for maximum heap memory. For stack , use –Xss to specify stack size for each thread.
6) If stack memory is filled up then you will get java.lang.StackOverFlowError . If there is no space left to allocate new Object in Heap memory then you will get java.lang.OutOfMemoryError: Java Heap Space.
Program to generate StackOverFlowError exception :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.j2eereference; public class StackOverflowErrorDemo{ public static void recursiveComputation(int count) { if(count == 0) return; else recursiveComputation(++count); } public static void main(String[] args) { StackOverflowErrorDemo.recursiveComputation(10); } } |
OutPut:
Exception in thread “main” java.lang.StackOverflowError
at com.j2eereference.StackOverflowErrorDemo.recursiveComputation(StackOverflowErrorDemo.java:13)
at com.j2eereference.StackOverflowErrorDemo.recursiveComputation(StackOverflowErrorDemo.java:13)
Program to generate OutOfMemoryError: Java heap space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.j2eereference; import java.util.ArrayList; import java.util.List; public class OutOfMemoryDemo { private static List<String> heapList=new ArrayList<>(); public static void main(String[] args) { while(true) { heapList.add(new String("Shobhna")); } } } |
OutPut:
Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at com.j2eereference
7) Stack memory allocation is simple as compared to heap memory allocation as Stack uses LIFO order,so stack memory is fast as compared to heap memory.
8) Stack memory is used by only threads whereas heap memory is used by whole application.
9) use stack when you know that how much memory is needed to allocate before compile time on the other hand, use heap if you are not sure about the amount of memory needed at runtime.