Thursday, September 15, 2016

Memory - Heap v/s Stack

  1. Heap Space
·         Part of memory allocated to JVM by OS
·         used by java runtime to allocate memory to Objects and JRE classes
·         Whenever we create any object, it’s always created in the Heap space
·          Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference. 
·         Any object created in the heap space has global access and can be referenced from anywhere of the application
·         java.lang.OutOfMemoryError: Java Heap Space when full. Before throwing this error garbage collector is run and if even then no space is available the error is thrown
·         heap size can be increased by using JVM options -Xms and -Xmx. Xms denotes starting size of Heap while -Xmx denotes maximum size of Heap in Java
·         you can’t change the size of Heap in Java dynamically, you can only provide Java Heap Size parameter while starting JVM
·         use either JConsole or Runtime.maxMemory(), Runtime.totalMemory(), Runtime.freeMemory() to query about Heap size programmatic in Java



  1. Java Memory Stack
·         used for execution of a thread
·         contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method. 
·         referenced in LIFO
·         Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method.
·         java.lang.StackOverFlowError when full
·         very less in size as compared to Heap Size

Garbage Collection and Java Heap

1.      New Generation of Java Heap is part of Java Heap memory where newly created object are stored
2.      During the course of application many objects created and died but those remain live they got moved to Old or Tenured Generation by Java Garbage collector thread
3.      Perm space of Java Heap is where JVM stores Meta data about classes and methods, String pool and Class level details
4.      Mechanism to reclaim heap space and is carried by a daemon thread called garbage collector
5.      We can’t trigger garbage collection. It is triggered by JVM whenever it feels the heap size has increased too much.
6.      System.gc() and Runtime.gc() are sent to JVM but does not guarantee they work
7.      Before removing an object finalize() method of that object and gives an opportunity to do any cleanup
8.      An object is available for garbage collection if it is not reachable by any live threads or references are null.
9.      Cyclic dependencies are not counted as the reference so if object A has a reference to object B and object B has a reference to Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.


No comments:

Post a Comment