WeakReference in Java

WeakReference, SoftReference and PhantomReference are added to the Java API long back but have not effectively used by most of the programmers. The reason being the less knowledge on the concept of how these APIs work for managing the references. Basically these APIs are helping the Garbage Collector to claim the memory looking at the reference to the objects. WeakReference objects are garbage collected at high priority then the SoftReference.¬†An object referenced only by weak references is considered unreachable (or “weakly reachable”) and so may be collected at any time.

What is WeakReference?

An object is eligible for garbage collection only when there is no reference pointing to that object or it has the weak reference. WeakReference is an API to indicate the JVM that the object referenced is less importance and can be garbage collected. You can consider references are like handle which is used for invoking the actual objects. If there is no reference for an object, then there is no way that the object will be used in the application. Then it is prefect candidate for the garbage collection. Here, not all the references are same. The garbage collector assigns point or value for each reference. WeakReferences are always garbage collected at first.

If you want to make a strong reference to be a weak reference, then pass the strong reference to the constructor of the appropriate reference objects, here it is WeakReference. WeakReference is defined under the package java.lang.ref. Two other related reference objects are SoftReference and PhantomReference.

Java Reference Types

WeakReference Example

Lets look at an example on how to define a weak reference.

Employee employee = new Employee(); // strong reference
WeakReference<Counter> weakCounter = new WeakReference<Employee>(employee); //making employee as weak reference
employee = null; // now Employee object is eligible for garbage collection

Now if you look at the above code, first line for creating the Employee object is a strong reference. This object can not be garbage collected because it holds the strong reference. In the second line, we are creating the WeakReference using the “employee” reference variable. When this reference is assigned to “null” in the third line, it is perfect candidate for the garbage collection.

These techniques would be very useful at the time when your application uses cache or any similar approach for storing large amount of objects for the shorter time, then you would probably require garbage collection to manage the memory efficiently.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*