Wednesday, 1 July 2015

Heap vs Stack Memory Java

Stack Memory Heap Memory
What? It's type of temporary memory used by JVM to store local method primitives variables, and method calls information. It's type of memory used by JVM to store references of objects (regardless where they are created) and String Pool.
Size? Small, It's very less compare to Heap. Big, It's very more compare to Heap.
Scope? Single Thread Multiple Threads
Shared? No, It is not shared between multiple threads. Each thread will have it's own stack memory. Yes, It is shared between multiple threads, so each thread can get reference of any object.
Example? Infinite Recursion :
public static void test(long a,long b){
   test(a++,b++);
}
Adding Infinite String in List/Set.
public static void test(){
      List list = new ArrayList();
      while(true){
          list.add(new String("Test"));
      }
}
Notification of Exceed Memory JVM will throw StackOverflowError JVM will throw OutOfMemoryError
Access Spped? Fast, Single thread will access it, so obviously it can be access more faster compare to Heap. Slow, Multiple thread will access it, so obviously it can be access slower compare to Stack.
How to Apply? JVM Option -Xss=10M, It's vary from version to version. by default 128KB for windows 64 bit. Oracle Docs JVM Option -Xms=512M (Initial Java heap size) and -Xmx=1024M (Maximum Java heap size)
How to Avoid? Try to avoid recursive code as much as possible. Recursion code can be always tranform into Interative.

Why? : Recursion vs Iteration
How? : Binary Search Alorithm
Make sure that any objects have not live/strong references behind your eyes which leads to Memory Leak.

Avoid open Streams, close them. (mostly with IO)
Avoid open connections, close them. (mostly with database operations)
Avoid new String(String s), alternative use new String().intern()
Garbage collected? No, Once a function call runs to completion, any data on the stack created specifically for that function call will automatically be deleted. Yes, Once all references for any object are null, it will be collected by GC which is run by JVM.
Common Points? Stack and Heap both are stored in the computer's RAM.

2 comments :

rajesh kinkhabwala said...

Great article.Gives in depth knowledge of How Java works.Keep it up buddy :-)

Vishal Zanzrukia said...

Thanks @Rajesh :) I am glad to hear such nice words :) It's great inspiration for me :)