Saturday, 31 October 2015

Garbage Collection

Garbage Collection- For automatic memory management
Any Object on heap which cannot be reached through a reference from the stack is "eligible for garbage collection".




Memory Leak(Soft leak)
  • An object is referenced on Stack even though it will never be used again 
  • Unused object is never freed


PermGen/MetaSpace
  • PermGen is part of heap until Java7. It is replaced by Metaspace from Java8.
  • Objects in PermGen will survive for ever. It is never Garbage collected. 
  • Application crashes if it runs out of memory.
  • Objects placed in PermGen
    • Internalized Strings- Strings placed in POOL for reuse. (in Java6 only)
    • Class Metadata
    • Application crashes with "out of PermGen" when
      • too many classes to load
      • too many internalized strings
      • Server application - When ever application is redeployed with minor changes, a new complete set of meta data is created. Metadata pertaining to prior deployments is still in the PermGen, but never referred. Hence, if an appln is redeployed number of times, eventually PermGen will runout of space. 
  •  MetaSpace
    • Meta data of the classes are placed
    • Not part of heap
    • Allocated out of your computers native memory(out side of jvm memory or heap memory)


  • Introduction
    • In java, programmer is responsible only for object creation and not for destruction of unused objects.  Jvm provides Garbage Collector to destroy no longer used objects. Because of garbage collector, the chances of java program failing with out of memory is very less.
    • It is part of jvm.
    • It is daemon thread to destroy unused objects
  • The  ways to make an object eligible for garbage collection
    • Nullifying the reference variable
    • reassigning the reference variable
    • Objects created inside a method (local variables will be destroyed after method execution completes)
      • Exception1: For a returned object, if there is reference is caller method, then it is not eligibile for GC
    • Island of isolation
      • If an object does not have any reference variable then it is always eligible for GC
      • Even though object having Reference variable still sometimes it may be eligible for GC, when all references are internal references.
eg:
class Test{
  Test i;
   public static void main(String[] args){
   Test t1=new Test();  Test t2=new Tests();
   t1.i=t2;  t2.i=t1;
   t1=null; t2=null
}
}

  • Methods for requesting jvm to run garbage collector
    • Once we make object eligible for GC, GC may not destroy right away. It will be destroyed only when JVM runs GC. Timing of when jvm runs GC varies from jvm to jvm and we cannot predict it.
    • Instead of waiting for jvm, we can request jvm to run GC. No guarantee that the jvm will accept the request, however in most cases it accepts.
    • System class 
      • System.gc() // Static method
    • Runtime Class
      • Runtime r=Runtime.getRuntime();
        • freeMemory(); //returns free memory present in heap in bytes
        • totalMemory(); //returns total heap memory in bytes
        • gc() // requests jvm to run GC. This is instance method.
  • finalization
    •  
Singleton Class:  Class where only one Object can be created.
eg: Runtime

Factory Method: A method in a class which returns object of the same class is called Factory Method
eg: Runtime r=Runtime.getRuntime();
import java.util.*
class Test{
   public static void main(String[] args){
      Runtime r=Runtime.getRuntime();
      System.out.println(r.totalMemory);
      System.out.println(r.freeMemory);
      for(int i=0; i<1000; i++){
           Date d=new Date();
           d=null;
   }
System.out.println(r.freeMemory);
r.gc();
System.out.println(r.freeMemory);
}

Note
  • Just before destroying an Object, Garbage collector always calls finalize() on that Object. For example, if String Object is eligible for GC, the String class finalize() will be executed, but not on the class where it was created. 
  • finalize() can be called explicitly by program as well. However, it will not destroy the object. Even in the given cases, GC will execute finalize() before destroying the object.
 Memory Leaks:
  • Objects which are no longer used by our program, and still not available for Garbage Collection called Memory Leaks.
  • Program will fail with out of memory error if memory leaks exist
  • To over come the problem, programmer have to make the no longer useful objects available for GC
  • Memory leaks is a purely a programmers mistake
  • Memory management tools to identify memory leaks
    • HP-J-METER
    • HP-OVO
    • J-PROBE
    • HP-PATROL
    • IBM-TIVOLI

Tuning JVM
  • -Xmx - to set Maximum heap size
  • -Xms - to set the starting heap size
    • eg: -Xmx512m -Xms150m  --mega bytes
  • -XX:MaxPermSize  - to set the size of the permgen
    • eg: -XX:MaxPermSize=256M
  • -verbose:gc  print to the console when a garbage collection takes place
  • Young Generation 
    • default 1.3 of heap size
    • -Xmn  - set the size of young generation
      • eg: -Xmn256m
  • -XX:HeapDumpOnOutOfMemory - Creates a heap dump file
  • -XX:MaxPermSize=256M  - set the size of perm gen 
  • -verbose:gc  - print to console when a garbage collection takes place
  • -Xmn  - set the size of the young generation
  • -XX:HeapDumpOnOutOfMemory - creates a heap dump file
 
 
 
Types of Garbage Collectors
  • Serial - uses single thread 
    • -XX: +UseSerialGC
  • Parallel - 
    • -XX: +UseParallelGC
  • Mostly Concurrent. There are 2 such collectors
    • -XX: +UseConcMarkSweepGC
    • -XX: +UseG1GC
  • Use -XX:+PrintCommandLineFlags to find out which is your default garbage collector




Permgen

Weak and soft references:
Weak reference - Reference that may not survive garbage collection. If a variable is declared as Weak, then the object is eligible for garbage collection even though there is variable referencing from stack. When garbage collection takes place, the variable may or may not survive.

Soft reference - Slightly stronger than weak reference. If a variable is declared as Soft, then the object is eligible for garbage collection even though there is variable referencing from stack. Garbage collection considers such variables only when there is real memory crunch.

WeakReference<Book> myBook=book1;
SoftReference<Book> myBook=book2;

These are used for cacheing scenarios.

WeakHashMap - It is implementation of a MAP that works exactly like regular hashmap, but the references between keys and values are Weak references. They are ideal for storing objects in memory. HashMap can be referenced by variable from Stack which is a Strong reference.

No comments:

Post a Comment