A WeakReference object is same as an ordinary object but differs only when garbage collection comes into picture.
How does garbage collection work?
When JVM is running out of memory, it triggers garbage collection, i.e. a process which reclaims any space used by dead objects. Dead objects can be thought of the ones which are not referenced from anywhere.
Now coming back to WeakReferece, it is a reference which is ignored by GC process. That is, if an object is only referenced by a weak reference, it will still be removed (collected as garbage).
Let’s take an example to clarify the point (http://en.wikipedia.org/wiki/Weak_reference)
import java.lang.ref.WeakReference;
public class ReferenceTest {
public static void main(String[] args) throws InterruptedException {
WeakReference r = new WeakReference(new String(“I’m here”))
WeakReference sr = new WeakReference(“I’m here”);
System.out.println(“before gc: r=” + r.get() + “, static=” + sr.get());
System.gc();
Thread.sleep(100);// only r.get() becomes null
System.out.println(“after gc: r=” + r.get() + “, static=” + sr.get());}
}
Output
before gc: r=I’m here, static=I’m here
after gc: r=null, static=I’m here
Practical usage:
When will I need to make an object as WeakReference?
In case there is some data which is good to have in memory but can be GCed if memory requirements occur. For example, say I have a list of Employees and each employee has address. The address details are not referenced as frequently as other details so I will mark the address as WeakReference object, as it can be re-fetched from database if required. And if JVM needs memory, it can reclaim the address space.