Until today, I wasn't aware of the fact that Java has four main types of references.
- Strong Reference : Default reference type that
Java
uses. - Weak Reference : If an object has a weak reference then
GC
reclaims this object’s memory in next run even though there is enough memory. - Soft Reference : If an object has a soft reference, then
GC
reclaims this object’s memory only when it needs some memory badly. - Phantom Reference : If an object has a phantom reference, then it's eligible for garbage collection. But, before GC, JVM puts the objects which are supposed to be garbage collected in a queue called
reference queue
.
I understood the basic concept and I wrote a small program to understand how each of the reference types work.
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
class User
{
public User info()
{
System.out.println("Info method invoked from User class");
return null;
}
}
public class ReferencesExample
{
public static void main(String[] args)
{
//Strong Reference
User userRefObj = new User();
System.out.println("1 :" + userRefObj.info());
// Weak Reference
WeakReference<User> weakref = new WeakReference<User>(userRefObj.info());
System.out.println("2 : " + weakref);
// Soft Reference
SoftReference<User> softref = new SoftReference<User>(userRefObj.info());
System.out.println("3 : " + softref);
// Phantom Reference
ReferenceQueue<User> refQueueObj = new ReferenceQueue<User>();
PhantomReference<User> phantomRef = new PhantomReference<User>(userRefObj.info(),refQueueObj);
System.out.println("4 : " + phantomRef);
}
}
Output :
1 :null
Info method invoked from User class
Info method invoked from User class
2 : java.lang.ref.WeakReference@15db9742
Info method invoked from User class
3 : java.lang.ref.SoftReference@6d06d69c
Info method invoked from User class
4 : java.lang.ref.PhantomReference@7852e922
Doubt : How do we decide which reference type to use and where exactly to use in a real world scenario ?