Saturday, August 16, 2014

WeakReference and SoftReference in JAVA

Today I am going to explain you about WeakReference and SoftReference in Java.
We have two classes named java.lang.ref.SoftReference and java.lang.ref.WeakReference defined in package java.lang.ref. Having knowledge about these classes will  assist you in Garbage Collection and result in better memory management in Java.
As we all know that Garbage Collector reclaims memory from objects which are eligible for garbage collection, but not many programmer knows that this eligibility is decided based upon which kind of references are pointing to that object. This is also main difference between WeakReference and SoftReference in Java. Garbage collector can collect an object if only weak references are pointing towards it and they are eagerly collected, on the other hand Objects with SoftReference are collected when JVM absolutely needs memory. 
Now let us understand WeakReference using an Example below:-
import java.lang.ref.WeakReference;

public class WeakReferenceExample {

 /**
  * @param args
  * @author Satish
  */
 public static void main(String[] args) {
  WeakReferenceExample references = new WeakReferenceExample();
  Employee employee = references.new Employee(1, "satish"); //Strong Reference
  WeakReference<Employee> weakReference = new WeakReference<Employee>(employee);//WeakRefernece
  System.err.println("This is Employee Object--"+employee);
  employee = null;//object is made eligible for garbage collection.
  System.err.println("This is Employee Object before GC execution--"+weakReference.get());
  /*Now as soon as you make employee object null Employee Object becomes eligible for
   * garbage collections as it doesnot have any Strong and only WeakReference pointing to that 
   * Object So in case of WeakReference when the gc will execute the Object will be gc'd*/
  System.gc();
  //Object will be gc'd now.
  System.err.println("This is Employee Object After GC execution--"+weakReference.get());

 }
 class Employee {
  final int id;
  final String name;

  public Employee(int id,String name) {
   this.id = id;
   this.name = name;
  }
 }

}

Now let us Understand SoftReference using an Example below:-
As I already explained that in case of SoftReference Object will be garbage collected but with delay and when JVM actually need memory.

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

public class SoftReferenceExample {

 /**
  * @param args
  * @author Satish
  */
 public static void main(String[] args) {
  SoftReferenceExample references = new SoftReferenceExample();
  Employee employee = references.new Employee(1, "satish"); //Strong Reference
  SoftReference<Employee> softReference = new SoftReference<Employee>(employee);//SoftRefernece
  System.err.println("This is Employee Object--"+employee);
  employee = null;//object is made eligible for garbage collection.
  System.err.println("This is Employee Object before GC execution--"+softReference.get());

  System.gc();
  //Here you can see that Object is still not gc'd and will be gc'd when JVM actually needs memory dislike WeakReference in
  //which Object will be gc'd when employee Object 
  //will be made null and GC executes;
  System.err.println("This is Employee Object After GC execution and before OOM--"+softReference.get());
  //now test SoftReference after making OOM.
  references.makeOutOfMemory();
  System.err.println("This is Employee Object after making OOM--"+softReference.get());

 }
 @SuppressWarnings({ "unchecked", "rawtypes" })
 private void makeOutOfMemory() {
  List list = new ArrayList();
  try {
   while (true) {
    list.add(new byte[100]); 
   }

  } catch (OutOfMemoryError e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 class Employee {
  final int id;
  final String name;

  public Employee(int id,String name) {
   this.id = id;
   this.name = name;
  }
 }

}


Hope you Guys will enjoy this post and will help you to understand References In java.
For those who don't know there are four kind of reference in Java :

  1. Strong reference
  2. Weak Reference
  3. Soft Reference
  4. Phantom Reference
In this post I have Explained first 3 references and will exaplain last one in my next post...
Thanks....