Sunday, November 29, 2015

MemoryOutOfError and StackOverflowError

                               MemoryOutOfError VS StackOverflowError
When you start JVM you define how much RAM it can use use for processing. JVM divides this into certain memory locations for its processing purpose, two of those are Stack & Heap
OutOfMemoryError is related to Heap. If you have large objects (or) referenced objects in memeory, then you will see OutofMemoryError. If you have strong references to objects, then GC can't clean the memory space allocated for that object. When JVM tries to allocate memory for new object and not enough space available it throws OutofMemoryError because it can't allocate required amount of memory.

How to avoid: Make sure un-necessary objects are available for GC
Important points to remember about Heap Space
  • Use Profiler and Heap dump Analyzer tool to understand Java Heap space and how much memory is allocated to each object.
  • Heap in Java generally located at bottom of address space and move upwards. whenever we create object using new operator or by any another means object is allocated memory from Heap and When object dies or garbage collected ,memory goes back to Heap space in Java.
  • Heap is divided into three main regions named as New Generation, Old or Tenured Generation and Perm space. New Generation of Java Heap is part of Java Heap memory where newly created object are stored, During the course of application many objects created and died but those remain live they got moved to Old or Tenured Generation by JavaGarbage collector thread on Major or full garbage collection. Perm space of Java Heap is where JVM stores Meta data about classes and methods, String pool and Class level details.
  • Java.lang.OutOfMemoryError: Java heap space error messages denotes that Java heap does not have sufficient space and cannot be expanded further while Java.lang.OutOfMemoryError: PermGen space error message comes when the permanent generation of Java Heap is full, the application will fail to load a class or to allocate an interned string.

StackOverflowError is related to stack. All your local variables and methods calls related data will be on stack. For every method call one stack frame will be created and local as well as method call related data will be placed inside the stack frame. Once method execution is completed, stack frame will be removed. ONE WAY to reproduce this is, have infinite loop for method call, you will see stackoverflow error, because stack frame will be populated with method data for every call but it won't be freed (removed).

How to avoid Make sure method calls are ending (not in infinite loop)

No comments:

Post a Comment