BackgroundIf you are acquainted with Java then you must have heard that objects are created on heap and there is automatic garbage collection in Java. In this post we will see the java memory allocation. Not everything is created on heap. Let's start with the basics. Whenever you run a new java process a new JVM is created that takes care of running your Java program. Like any other process your operating System will provide this JVM instance some memory to run. You can also specify heap size of your Java program in your jvm arguments.
Java memory allocation
You can use following options to alter JVM memory
- -Xms<size> set initial Java heap size (Eg. java -Xms1g TestProgram)
- -Xmx<size> set maximum Java heap size (Eg. java -Xmx2g TestProgram)
- -Xss<size> set java thread stack size (Eg. java -Xss4m TestProgram)
StackStack is where local variables are stored and that includes primitive types and object references. Each thread will have it's own private stack (which you can define in Java with -Xss JVM parameter). Each method will create it's own section on this stack for maintaining scope. This is called stack frame. Whenever a local variable is in methods scope it is pushed to this stack frame and when it is out of the scope it is poped out. Note this is all scope based. There is no concept of garbage collection in stacks.
Heap is where your objects are created (memory is allocated for the object). Whenever you create a new instance of a class using new keyword it is created on this heap. This object will be garbage collected when it is no longer referenced from any of the GC roots.
Difference between Stack and Heap memory
- As mentioned earlier Stack stores local variables and object references where as heap stored the actual object instance.
- If stack memory is filled up JVM will shutdown throwing java.lang.StackOverFlowError error where as if heap memory is filled JVm will shutdown throwing java.lang.OutOfMemoryError error.
- Each thread will have it's own private stack. Meaning each stack memory is private to some thread where as heap area is shared among all the threads.