Wednesday 26 August 2015

Java memory allocation

Background

If 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
  1. -Xms<size>      set initial Java heap size (Eg. java -Xms1g TestProgram)
  2. -Xmx<size>      set maximum Java heap size (Eg. java -Xmx2g TestProgram)
  3. -Xss<size>        set java thread stack size (Eg. java -Xss4m TestProgram)
Java memory is of two types.
  1. Stack
  2. Heap

Stack

Stack 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

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

  1. As mentioned earlier Stack stores local variables and object references where as heap stored the actual object instance.
  2. 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.
  3. 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.

Related Links

t> UA-39527780-1 back to top