What are weak, soft and phantom references in Java, and how do they differ?
They are three ways of holding a reference to an object that says how strongly the collector should feel about it.
A weak reference says that the object should be collected as soon as nothing else refers to it. It is the right one for a cache that is keyed by objects, where the cache should not keep the keys alive.
A soft reference says that the object should be collected only when the memory is running low. It is the right one for a cache that you want to keep as long as there is room for it.
A phantom reference does not give you the object at all. The method get always gives back null, and the reference is only useful for finding out that the object has been collected, so that you can do some clean up.
import java.lang.ref.WeakReference;
import java.lang.ref.SoftReference;
import java.lang.ref.PhantomReference;
public class Main {
public static void main(String[] args) {
Object object = new Object();
WeakReference<Object> weak = new WeakReference<Object>(object);
SoftReference<Object> soft = new SoftReference<Object>(object);
PhantomReference<Object> phantom = new PhantomReference<Object>(object, null);
System.out.println("the weak reference has : " + (weak.get() != null));
System.out.println("the soft reference has : " + (soft.get() != null));
// The object is still held by the local variable.
object = null;
// A phantom reference never gives the object back.
System.out.println("the phantom reference has : " + (phantom.get() != null));
}
}
So how do they differ? They differ in how hard the collector tries to keep the object.
A strong reference, which is the normal one, means the object stays alive for as long as the reference exists. A weak reference means the object goes as soon as the strong references are gone. A soft reference means the object goes only when the collector needs the memory. And a phantom reference is the weakest of all, because the object is already gone by the time you can see the reference.
The next question in this topic looks at how to use the weak one properly.