References in Java - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Wednesday, August 17, 2016

References in Java

References classes are important in context of garbage collection. Java does not put burden of memory management on programmers. Java automatically reclaim the memory from objects which are eligible for garbage collection. Garbage collector thread does this for you. This thread is responsible for sweeping out unwanted object from memory, but you have no control over garbage collector thread. You can't run it whenever you want. It is up to JVM which decides when to run garbage collector thread. you can just send a request to JVM to run garbage collector thread using System.gc() or Runtime.getRuntime().gc() method.

After introduction of java.lang.ref package, programmer have little control over garbage collector when your object will be garbage collected.

Java has 4 types of references based on objects are garbage collected.

In order of strongest to weakest these references are:

  1. Strong Reference
  2. Soft Reference
  3. Weak Reference
  4. Phantom Reference

Lest understand these references in details.

1.Strong Reference

Strong reference is most simple and every programmer use it in day by day programming life. Any object in memory which has active strong reference is not eligible for garbage collection. For example,

public class MyClass {

 public static void main(String[] args) {
  String stringObject = "XYZ"; // strong reference
  stringObject = null; // Now stringObject refer to null, so it is
                                    // available for garbage collection.
 }
}

In the above code snippet, String stringObject = "XYZ" , reference variable stringObject has strong reference variable to String object "XYZ". At this point of time, this object can't be garbage collected.

Once you make the reference variable stringObject to point to null, now object is available for garbage collection, because it is not having any active reference on it. This object is most likely to be garbage collected when JVM decides to run garbage collector thread.

Look at below diagram for precise understanding.

Strong Reference

2.Soft Reference

The objects which have soft referenced will not garbage collected(even though they are available for garbage collection) util JVM badly needs memory. Soft Reference looks perfect for implementing caches, so when JVM needs memory it removes objects which have only SoftReference pointing toward them. You can create soft reference on existing object using java.lang.ref.SoftReference class.

import java.lang.ref.SoftReference;

class A {
 // members variable and methods
}

public class DemoClass {
 public static void main(String[] args) {
  A a = new A(); // strong reference
  // creating soft reference to A-type object, pointing to strong
  // reference "a"
  SoftReference<A> soft = new SoftReference<A>(a);
  a = null; // now object a is available for garbage collection but only
     // when JVM badly needs memory

  a = soft.get();
 }
}

In the above code snippet, SoftReference variable soft internally referring to A-type object. After making strong reference 'a' to point to null. Object to which reference variable a was pointing earlier becomes eligible for garbage collection. But it will be garbage collected only when JVM badly needs memory, because its softly referenced by soft variable.

You can retrieve reference of softly referenced object using get() method of SoftReference class. it will return null if the object is garbage collected.

Look at below diagram for precise understanding.

soft Reference

3.Weak Reference

The objects which have weak reference are easily available for garbage collection. An object that is identified as only weakly reachable will be garbage collected at the next garbage collection cycle. JVM does not show any regard toward weak reference.

You can create weak reference on existing object using java.lang.ref.WeakReference class.

import java.lang.ref.WeakReference;

class A {
 // members variable and methods
}

public class DemoClass {
 public static void main(String[] args) {
  A a = new A(); // strong reference
  // creating weak reference to A-type object, pointing to strong
  // reference "a"
  WeakReference<A> weak = new WeakReference<A>(a);
  a = null; // now object a is available for garbage collection

  a = weak.get();// you can retrieve back the object which have reference
 }
}

WeakReference is great for storing meta data e.g. storing ClassLoader reference. If no class is loaded then no point in keeping reference of ClassLoader, a WeakReference makes ClassLoader eligible for Garbage collection as soon as last strong reference removed.

You can retrieve reference of weakly referenced object using get() method of WeakReference class. it will return null if the object is garbage collected.

Look at below diagram for precise understanding.

Weak Reference

4.Phantom Reference

The objects which are referenced by phantom reference are eligible for garbage collection.But, before removing them from the memory, JVM puts them in a queue called ReferenceQueue.They are put in a reference queue after calling finalize() method on them. You can’t retrieve back the objects which are being phantom referenced. That means calling get() method on phantom reference always returns null.

You can create phantom reference on existing object using java.lang.ref.PhantomReference class.

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

class A {
 // members variable and methods
}

public class DemoClass {
 public static void main(String[] args) {
  A a = new A(); // strong reference
  // creating reference Queue
  ReferenceQueue<A> referenceQueue = new ReferenceQueue<A>();
  // Creates a phantom reference that refers to the A-type object and is
  // registered with the given queue.
  PhantomReference<A> phantom = new PhantomReference<A>(a, referenceQueue);
  a = null; // now object a is available for garbage collection. But this
   // object is kept in referenceQueue before removing it from
   // the memory.

  a = phantom.get();// always return null
 }
}

No comments :

Post a Comment